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
Related
This question already has answers here:
Get first date of current month in java
(11 answers)
Closed 1 year ago.
Im working on a project that visually displays statistical data from each month and week and i dont know how to elegantly renew the dates of each week and month.
For example, i want to display this months data. I have to make two date variables in Java. The first one being 1.5.2021 and the second one being todays date. I dont know how to elegantly set the first variable to 1.x.xxxx without making a string out of the current date first and then cuting it, doing some numerics with it and merging it back together to 1.5.2021.
Same goes for weekly statistics where i need the Monday date and the Sunday date, for example today being Monday 10.5.2021 and the end on 17.5.2021.
So my idea is to get current date to string format, slice it, convert it to int, calculate the desired dates and the put it back to string(no need to go back to datetype since its gonna be used for querying).
Well, you should definitely take a look at the classes within the java.time package.
In your case, your current date could be a LocalDate instance, for example with the following line:
LocalDate.of(2021, 5, 1);
And then you could just use the withDayOfMonth method to get a new LocalDate instance with the day of the month set to 1:
LocalDate currentDate = LocalDate.now();
LocalDate firstOfMonth = currentDate.withDayOfMonth(1);
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)
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 2 years ago.
Improve this question
I am trying to get the date and time value from a Date method in the java.time.LocalDateTimeclass. I have stored that value in a variable and I want to use it to set the parameter for an SQL query, but I am unable to extract the value. The code won't compile. I tried this:
LocalDateTime dt = LocalDateTime.now();
query.setParameter("test", Date.valueOf(dt)); //error thrown here. I want to extract the current date and time ( hours, minutes, seconds) value stored in the dt variable
There is no Date.valueOf(LocalDateTime), there is only Date.valueOf(LocalDate).
You need to use LocalDate directly or you can convert the LocalDateTime to LocalDate by calling toLocalDate on it.
Notice that java.sql.Date is actually not used for representing time-components like hours, minutes, seconds and so on. If you want both (date and time), then use java.sql.Timestamp, which even has the method that you want: Timestamp.valueOf(LocalDateTime).
Just a side note: The class for time-only is java.sql.Time.
You should be using a plain java.time solution without any relation to the outdated API around java.util.Date. Date.valueOf(LocalDate) just exists to make legacy code compatible with the modern datetime API (that is java.time).
Since you haven't clarified which time your question is about, I can just show different possibilities.
Please note that LocalDateTime is not suitable for catching timestamps because it does not contain information about your time zone or an offset, but you can add one if necessary:
public static void main(String[] args) {
// get "now" without any time zone or offset information
LocalDateTime now = LocalDateTime.now();
// extract the date part
LocalDate today = now.toLocalDate();
// extract the time-of-day part
LocalTime timeOfNow = now.toLocalTime();
// then print the single parts (date and time of day)
System.out.println("Today is " + today + " and now is " + timeOfNow + " that day");
// print the full timestamp
System.out.println("Full date and time are now " + now);
// or print the epoch milliseconds (A ZONE OR AN OFFSET IS NEEDED THEN)
System.out.println("Moment in time of now is "
+ now.toInstant(ZoneOffset.UTC).toEpochMilli() + " in UTC");
}
The output of this is (see the output for execution time ;-) )
Today is 2020-08-13 and now is 15:04:46.728 that day
Full date and time are now 2020-08-13T15:04:46.728
Moment in time of now is 1597331086728 in UTC
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 3 years ago.
Improve this question
I am trying to parse timestamps using the format "yyyymmddHHssmm".
I have two such time stamps:
String timeStamp1 = "20190612221303"//this means 12June2019 10:13:03pm
String timeStamp2 = "20190512222303"//this means 12May2019 10:23:03pm
So I am trying to convert these timestamp string to java date using the following :
Date date1= new SimpleDateFormat("yyyymmddHHssmm").parse(timeStamp1);
Date date2 = new SimpleDateFormat("yyyymmddHHssmm").parse(timeStamp2);
So obviously when I do a
System.out.println(date1.getTime() > date2.getTime());
I would expect the above statement to print true.
But alas it prints false.
Inface the .getTime() of Date prints 1547310793000 for date1 and 1547310803000 for date2, which is obviously incorrect.
Could someone point out what is going on here.
In the format string, you have mm twice: yyyymmddHHssmm. The first occurrence should be MM, for month of year.
What is happening is that you are using
m Minute in hour
And your TimeStamp it is parsing with date
Sat Jan 12 22:03:13 Date1
Sat Jan 12 22:03:23 Date2
You need to use
M Month in year
Check more in the documentation
The format that you have used:yyyymmddHHssmm is ambiguous.
I believe the 5th and 6th characters are used to define months.
Use MM in caps for that.
You have used small mm, which means minutes
Your String passed to SimpleDateFormat should be yyyyMMddHHmmss . Take look here which letter stands for which thing in that formatter. https://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 4 years ago.
Improve this question
I have been working on a simple dictionary based android application so i thought to search for best practices to be used in the development. So i searched for the best methods for getting time and date but i found so many methods all resulting into date and time.
For example: Java - How to get current time and date
Here i found multiple methods to get the time and date with formatting as well.
Code Snippets
For java.util.Date, just create a new Date()
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date date = new Date();
System.out.println(dateFormat.format(date)); //2016/11/16 12:08:43
For java.util.Calendar, uses Calendar.getInstance()
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Calendar cal = Calendar.getInstance();
System.out.println(dateFormat.format(cal)); //2016/11/16 12:08:43
For java.time.LocalDateTime, uses LocalDateTime.now()
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss");
LocalDateTime now = LocalDateTime.now();
System.out.println(dtf.format(now)); //2016/11/16 12:08:43
For java.time.LocalDate, uses LocalDate.now()
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy/MM/dd");
LocalDate localDate = LocalDate.now();
System.out.println(dtf.format(localDate)); //2016/11/16
Why there are so many methods of getting date time in java?And Also what's the best method of getting the date and time?
Because date and time are complicated things like how to deal with currency and how to convert text to bytes and back.
You should be using the java.time package introduced in Java 8, as they've fixed things and tried to make it less annoying and weird. It was based on Joda-Time which is a well thought out library.
Date and Calendar are parts of the old time/date API, although there wasn't that much of an API, the classes were stuck to java.util and there were lots of design issues. They still work, but you shouldn't really use them in new code. Not because they're deprecated (they're not), but because they're bad. Imagine Date is to Instant like Vector is to ArrayList.
Date can give you the date and time, but you can't do much else with it. Calendar makes it possible to manipulate the date and time with things like skipping to next Wednesday, or adding a month (which is a number of days depending on the current month). As others have said, LocalDate(Time) is only available from API level 26 but has specific methods for manipulating the date (and time) instead of Calendar's function(field name, amount) style.
I suggest using Calendar.
Date is Deprecated or not suggest.
LocalDate and LocalDateTime required API 26.