Read a time from file in java [closed] - java

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
I am doing a work for the university and I have to read many lines from file a with that format:
3ld4R7 4:27 3475
Everything is correct, each line represents a song, the first string is the name, the second the duration and the third the popularity. However, I don't know exactly what type I can choose for the time. Then, I have to do many operations with the time (minutes, seconds, hours). I don't know if there is a class in Java libraries for that such as Time or something like that. Any help is thanked!!!

java.time.Duration
The Duration class of java.time, the modern Java date and time API, is the class for — well, the name says it already. Unfortunately parsing a string like 4:27 into a Duration is not built-in. My preferred trick is:
String durationString = "4:27";
String isoString = durationString.replaceFirst("^(\\d+):(\\d+)$", "PT$1M$2S");
Duration dur = Duration.parse(isoString);
System.out.println(dur);
Output:
PT4M27S
Read as a period of time of 4 minutes 27 seconds. The Duration.parse method requires a format known as ISO 8601, an international standard. And Duration.toString(), implicitly called when we print the Duration, produces ISO 8601 back. It goes like what you saw, PT4M27S. So in my code, the first thing I do is convert your input from the file to ISO 8601 format, which I then parse.
If you want to format the duration for display, for example back in the same format as in the file:
System.out.format("%d:%02d%n", dur.toMinutes(), dur.toSecondsPart());
4:27
Links
Oracle tutorial: Date Time explaining how to use java.time.
Wikipedia article: ISO 8601

There is such a library in Java and more than one.
Try java.util.Date library and SimeplDateFormatter class to parse the date-time objects in a specific way according to the strings.
For example:
DateFormat formatter = new SimpleDateFormat("MM/dd/yy h:mm a");
Date date = (Date)formatter.parse(date)

Related

Read date from webpage to Selenium java [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I am working on Selenium Java, I need to get the following date format without the time, as a string in selenium java to validate whether it is up to date with the published date. I used getText() method from the website by splitting from the time and date. Is there any other best ways rather than this solution!
java.time
Edit: I have added more explanation and more code lines.
There’s a little challenge in the fact that the string on the website does not include year. One simple way to handle it is:
ZoneId websiteTimeZone = ZoneId.of("America/Lower_Princes");
DateTimeFormatter formatter
= DateTimeFormatter.ofPattern("dd-MMM HH:mm", Locale.ENGLISH);
String stringFromWebsite = "06-Feb 06:37";
MonthDay today = MonthDay.now(websiteTimeZone);
System.out.println("Today is " + today);
MonthDay date = MonthDay.parse(stringFromWebsite, formatter);
System.out.println("Date from website is " + date);
if (date.equals(today)) {
System.out.println("It’s up to date");
} else {
System.out.println("It’s *NOT* up to date");
}
When I ran today (March 12), the snippet printed:
Today is --03-12
Date from website is --02-06
It’s *NOT* up to date
A MonthDay is a month and day of month without year. The advantage of using this class is we don’t need concern ourselves with year. A possible drawback is we can’t compare two such objects determine which one is before or after the other one. Such a comparison would require knowing the year of each one.
We need to know the time zone that the website uses since it is never the same date everywhere on Earth. Please insert the correct one where I put America/Lower_Princes.
I am parsing the string from the website into a MonthDay using a DateTimeFormatter with format pattern dd-MMM HH:mm since lower case d is for day of month, M is for month, H for hour of day and lower case m for minut of the hour. Since I am parsing into a MonthDay, the time is ignored (only its syntax still checked). In the print --03-12 means March 12 and --02-06 similarly February 6 (the date from the website). Since they are not the same, the code prints that the website is not up to date.
A more advanced solution might check if the date is a few days before or after today’s date and/or also look at the time.
Links
Oracle tutorial: Date Time explaining how to use java.time.
Stack Overflow question How do I simply parse a date without a year specified?
You can use selenium's getText(), in order to acquire the value as a String.
Afterwards you can use Java's DateTimeFormatter, to parse this date, and transform it to the format you want

How to parse duration format from duration in JAVA? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
I have a duration format which is like 0DT3H10M. So need to know how to parse this kind of data.
I want 0 Days 3 Hours and 10 Minutes from 0DT3H10M
in a specific format.
We can manually parse it by a character which is working fine but is there any other way or library available for this in android/java?
Duration
I will guess that string represents a duration of three hours and ten minutes.
Unfortunately that string fails to comply with the ISO 8601 standard used by default in the java.time classes Duration and Period. The standard starts all such strings with a P. And the standard separates any years-months-days from any hours-minutes-seconds with a T. So your input of three hours and ten minutes would be PT3H10M.
You will need to parse the string with your own code. Then use the extracted values to set the value of a java.time.Duration object.
You may be able to get away with simply prepending a P to comply with the standard. I hesitate to recommend this only because you would need to see the range of possible values you might receive to verify this approach would work.
Duration.parse( "P" + "0DT3H10M" )
Tip: Educate the publisher of your input data about ISO 8601.

Can I have more control on zone offset formatting at DateTimeFormatter [duplicate]

This question already has answers here:
SimpleDateFormat with TimeZone
(6 answers)
Closed 4 years ago.
Currently we are using
DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSX")
To format the time range to an external vendor for a range of data, for India, that formatter will give time like this:
2018-04-26T00:00:00.000+0530
However, my vendor say they cannot accept this format and it have to look like
2018-04-26T00:00:00.000+05:30
However, look like in DateTimeFormatter, whatever I choose Z/z/X/x, I don't get that format of offset. Just wonder is that a way to customize the offset to be HH:mm?
Or, I need to get the offset in second and work that our myself?
It is three x. Just tried with JavaRepl:
java.time.format.DateTimeFormatter
.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSxxx")
.withZone(java.time.ZoneId.systemDefault())
.format(java.time.Instant.now())
Results in
java.lang.String res10 = "2018-04-27T11:06:50.648+00:00"
After some trial and error, I saw that this is also documented in the API documentation of DateTimeFormatter but it is not easy to find (buried in a lot of other text):
Three letters outputs the hour and minute, with a colon, such as '+01:30'
DateTimeFormatter API Documentation

Working out time between 7am to 3:30pm - JAVA [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
I've created this program to calculate the time between startWork and finishWork
but I cant seem to figure out how to calculate time...
This is my Interface.
Just wanting to know a way of approaching this calculation.
Thanks
Use the Duration class from java.time to represent your working time. Let Duration.between() do the calculation for you, passing two LocalTime or two ZonedDateTime objects to it as appropriate. The latter will take transitions to and from summer time (DST) into the calculation if such a transition happens during the working hours.
If the time is entered as for example 1530 or 3:30pm, define a DateTimeFormatter to parse it into LocalTime.
Duration objects can be summed using its plus method, so you can calculate the hourly and monthly working time and so on.
To format the working time into for example 8.5 (for 8 hours 30 minutes), use the toMinutes method, then convert to double before you divide by 60 (I would declare the constant 60 as final double minutesPerHour = TimeUnit.HOURS.toMinutes(1);).
java.time
java.time is the modern Java date and time API. It came out nearly 4 years ago to replace the outdated and poorly designed date and time classes from Java 1.0 and 1.1 from the last years of the previous millennium.
Link: Oracle Tutorial trail Date Time
Use java.time as suggested by Ole V.V.:
String time1 = "07:00:00";
String time2 = "15:30:12";
LocalTime t1 = LocalTime.parse(time1);
LocalTime t2 = LocalTime.parse(time2);
Duration diff = Duration.between(t1, t2);
System.out.println(diff.toString());
Prints:
PT8H30M12S

How to handle time in Java [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 5 years ago.
Improve this question
I'm working on a functionality related to job scheduling in Java, where I'm required to schedule jobs based on days, weeks, or hours.
I'm running into 2 problems:
What is a good representation/library to handle a duration of time (not date)?
What is a good library to parse a text representation of time, i.e. 2d 3wk for 3 weeks and 2 days? similary to what JIRA has for their.
I'm thinking this must've been done before, but I can't seem to find the correct word to google it.
The JODA time library http://joda-time.sourceforge.net/ gives some nice Java time functionality. You may have to write some regular expressions to parse the type of text strings you're talking about though.
For scheduling the jobs, the Quartz scheduler http://www.opensymphony.com/quartz/;jsessionid=LDKHONNCOPJC may be useful to you.
Joda Time is THE reference for handling date in Java.
Have a look at Quartz, it s a powerful cron like system for Java.
You could parse a jira style time string into seconds using Joda time using something like this:
import org.joda.time.format.*;
import org.joda.time.;
import java.util.;
public class JiraStyleTimeParser
{
public static void main(String[] args)
{
String example = "1h 1m 30s";
MutablePeriod parsedPeriod = new MutablePeriod();
PeriodFormatter formatter = new PeriodFormatterBuilder()
.appendDays().appendSuffix("d")
.appendSeparator(" ")
.appendHours().appendSuffix("h")
.appendSeparator(" ")
.appendMinutes().appendSuffix("m")
.appendSeparator(" ")
.appendSeconds().appendSuffix("s")
.printZeroAlways()
.toFormatter();
PeriodParser parser = new PeriodFormatterBuilder()
.appendDays().appendSuffix("d")
.appendSeparator(" ")
.appendHours().appendSuffix("h")
.appendSeparator(" ")
.appendMinutes().appendSuffix("m")
.appendSeparator(" ")
.appendSeconds().appendSuffix("s")
.printZeroAlways()
.toParser();
int working = parser.parseInto(parsedPeriod, example,0, new Locale("en"));
System.out.println(formatter.print(parsedPeriod));
Duration theduration = parsedPeriod.toPeriod().toStandardDuration();
System.out.println("period in seconds: " + theduration.getStandardSeconds());
}
}
The nicest way to use Quartz is probably by using the interface to it that Spring Framework provides, here's a link to the reference manual.
have a look at Joda
Joda-Time provides a quality replacement for the Java date and time
classes. The design allows for multiple calendar systems, while still
providing a simple API. The 'default' calendar is the ISO8601 standard
which is used by XML. The Gregorian, Julian, Buddhist, Coptic,
Ethiopic and Islamic systems are also included, and we welcome further
additions. Supporting classes include time zone, duration, format and
parsing.
java.time
Use the java.time classes classes found bundled with Java 8 and later and back-ported to earlier versions.
Duration
To represent a span of time with a granularity of seconds-minutes-hours-days, use Duration.
Period
To represent a span of time with a granularity of days-months-years, use Period.
ISO 8601
Also, study up on standard ISO 8601 formats for strings representing date-time values.
For spans of time, the standard uses the format PnYnMnDTnHnMnS where P marks the beginning and T separates any years-months-days from any hours-minutes-seconds. So an hour and a half is PT1H30M.
The java.time classes use ISO 8601 standard formats by default when parsing and generating strings.
String output = duration.toString();
PT1H30M
Duration duration = Duration.parse( "PT1H30M" );
ThreeTen-Extra
See the ThreeTen-Extra project for more classes such as Interval, a plural amount of Days & Weeks & Months & Years, quarters, and standard ISO 8601 weeks.

Categories

Resources