Getting the value of time from a LocalDateTime class wont compile [closed] - java

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

Related

Java why does Calendar.get(Calendar.DST_OFFSET) give 0 during daylight savings time?

I have a Calendar object that corresponds to 2021-07-05T18:00:00.000-04:00 (Eastern Daylight Time). Yet Calendar.get(DST_OFFSET) and Calendar.getTimeZone().getDSTSavings() both give 0. It should be 1 hour. What am I missing or what am I going wrong? All the other methods I play with are returning the expected values.
I am creating the Calendar using setTimeInMillis() and TimeZone using offsets. Is that the reason it is not working? The displayed civil times are always right...
As much as I would like to use the new Java time I am using Java for Android. Last I checked only the most recent versions of Android support the new Java time. They may eventually add support to their older versions.
One problem is that the input defines an offset from UTC, but not a real time zone with specific rules (like if DST is applied at all and if it is, when will DST be applied).
Calendar is clearly not capable of handling those rules, the class (and probably the entire API) was not designed to be.
That's one of the reasons for java.time having been introduced in Java 8.
Here's some example use of java.time in a situation like yours:
public static void main(String[] args) {
// example String in ISO format
String dateString = "2021-07-05T18:00:00.000-04:00";
// define your time zone
ZoneId americaNewYork = ZoneId.of("America/New_York");
// parse the (zone-less) String and add the time zone
ZonedDateTime odt = OffsetDateTime.parse(dateString)
.atZoneSameInstant(americaNewYork);
// then get the rules of that zone
long hours = americaNewYork.getRules()
// then get the daylight savings of the datetime
.getDaylightSavings(odt.toInstant())
// and get the full hours of the dst offset
.toHoursPart();
// use a formatter to format the output (nearly) as desired
System.out.println(odt.format(DateTimeFormatter.ISO_ZONED_DATE_TIME)
+ " has a daylight saving offset of "
+ hours);
}
This prints
2021-07-05T18:00:00-04:00[America/New_York] has a daylight saving offset of 1
EDIT:
Your comment made me provide a similar version that uses a long as input:
public static void main(String[] args) {
// example String in ISO format
long input = 1625522400000L;
// create an Instant from the input
Instant instant = Instant.ofEpochMilli(input);
// define your time zone
ZoneId americaNewYork = ZoneId.of("America/New_York");
// then get the rules of that zone
long hours = americaNewYork.getRules()
// then get the daylight savings of the Instant
.getDaylightSavings(instant)
// and get the full hours of the dst offset
.toHoursPart();
// use a formatter to format the output (nearly) as desired
System.out.println(ZonedDateTime.ofInstant(instant, americaNewYork)
.format(DateTimeFormatter.ISO_ZONED_DATE_TIME)
+ " has a daylight saving offset of "
+ hours);
}
The output is just the same as in the above example.
in a java bug tracker you will find your problem.
During the "fall-back" period, Calendar doesn't support disambiguation and the given local time is interpreted as standard time.
To avoid the unexpected DST to standard time change, call add() to reset the value.
you can resolve it by replacing set() with
cal.add(Calendar.MINUTE, -cal.get(Calendar.MINUTE));

Java date time subtraction [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 2 years ago.
Improve this question
String date1 = "2020/05/08 16.38.37"
String date2 = "2020/04/08 20.18.10"
I wish to subtract complete date1 with complete date2 (date and time both included) and get the result in hours in java .
How to proceed ?
Knowing how many hours are between 2 given timestamps is not possible unless you tell me where on the planet you want to do the math for. For example, if you ask me the minutes between 01:30 and 03:30, the answer would seem to be 120, but if due to daylight savings that so happens to be exactly the night where the clocks are moved an hour forward, the actual correct answer'd be 60.
If you never want that kind of adjustment, UTC doesn't 'suffer' from weird adjustments like this, so you can always elect to do the math in the UTC zone.
Thus, the steps:
parse your strings (which represent 'local' date/times, given that they include no timezone info at all) into LocalDateTime objects.
Zone these 2 objects by turning them into ZonedDateTime objects at a zone of your choosing.
Now ask the API to calculate the hours, minutes, whichever one you prefer between the two.
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy/MM/dd HH.mm.ss");
ZoneId zone = ZoneId.of("Europe/Amsterdam");
LocalDateTime input1 = LocalDateTime.parse("2020/05/08 16.38.37", formatter);
LocalDateTime input2 = LocalDateTime.parse("2020/04/08 20.18.10", formatter);
ZonedDateTime zoned1 = input1.atZone(zone);
ZonedDateTime zoned2 = input2.atZone(zone);
Duration duration = Duration.between(zoned1, zoned2);
long hours = duration.toHours();
System.out.println(hours);
the above would print -716 (as in, the first stamp is at least 716 hours, and less than 717 hours, before the second.... at least, if you ask someone living in Amsterdam).
NB: If you want to talk about weeks, months, etc - you want Period and not Duration.
java.time
First don’t keep your dates and times as strings in your program. Just as you don’t use strings for keeping your numbers and Boolean values (I hope), you shouldn’t for dates and times either. Use proper date and time types from java.time, the modern Java date and time API.
Assuming that your dates and times are in some well-defined time zone, I suggest using ZonedDateTime for them.
ZoneId zone = ZoneId.of("America/Montreal");
ZonedDateTime dateTime1 = ZonedDateTime.of(2020, 5, 8, 16, 38, 37, 0, zone);
ZonedDateTime dateTime2 = ZonedDateTime.of(2020, 4, 8, 20, 18, 10, 0, zone);
Finding the difference is a one-liner:
long diffHours = ChronoUnit.HOURS.between(dateTime2, dateTime1);
System.out.println("Difference in hours: " + diffHours);
Output from this example snippet is:
Difference in hours: 716
Please insert your desired time zone where I put America/Montreal. Choosing a different time zone may cause us to get an hour more or fewer if the transition to or from summer time (DST) lies between the two dates.
Parsing date-time input
If your dates and times are string input, the first thing you need to do with them is parse them. An example:
DateTimeFormatter inputFormatter = DateTimeFormatter.ofPattern("uuuu/MM/dd HH.mm.ss");
String string1 = "2020/05/08 16.38.37";
String string2 = "2020/04/08 20.18.10";
ZonedDateTime dateTime1 = LocalDateTime.parse(string1, inputFormatter).atZone(zone);
ZonedDateTime dateTime2 = LocalDateTime.parse(string2, inputFormatter).atZone(zone);
System.out.println("Date and time 1: " + dateTime1);
System.out.println("Date and time 2: " + dateTime2);`
Date and time 1: 2020-05-08T16:38:37-04:00[America/Montreal]
Date and time 2: 2020-04-08T20:18:10-04:00[America/Montreal]
Link
Oracle tutorial: Date Time explaining how to use java.time.

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

Convert java.time.LocalDateTime SE 8 to timestamp [duplicate]

This question already has answers here:
Convert LocalDate to LocalDateTime or java.sql.Timestamp
(7 answers)
Closed 4 years ago.
How do you convert a Localdatetime to timestamp? I want to use the new SE 8 date api because it is better than the util date and calendar. I plan to use localdatetime throughout my program and then place that date into a mysql database. I have looked for an answer but there doesn't seem to be very many questions and answers for java.time. This is a little of the code that I am testing. This is as far as I got.
LocalDateTime c = LocalDateTime.now();
java.sql.Timestamp javaSqlDate = new java.sql.Timestamp(c.getLong());
I think I need to convert it into a long first, but I don't know how. The api allows for converting individual elements like month and day, but not for the whole date. Since I'm already here, how do you convert back from timestamp? Should I just use jodatime?
I tried this:
LocalDateTime c = LocalDateTime.now();
ZoneId zoneId = ZoneId.systemDefault();
System.out.println("this:" + c);
java.sql.Timestamp javaSqlDate = new java.sql.Timestamp(c.atZone(zoneId).toEpochSecond());
pst.setTimestamp(2, javaSqlDate);
This only saves the date around 1970. The system.print prints the current date correctly. I want it to save the current date.
LocalDateTime l = LocalDateTime.now();
Timestamp t = Timestamp.valueOf(l);
Source: https://coderanch.com/t/651936/databases/Convert-java-time-LocalDateTime-SE
First of all, you should decide if you really want to use LocalDateTime.
Below are some explanations about the difference, taken from here:
<...> LocalDateTime is not a point on the time line as Instant is, LocalDateTime is just a date and time as a person would write on a note. Consider the following example: two persons which were born at 11am, July the 2nd 2013. The first was born in the UK while the second in California. If we ask any of them for their birth date it will look that they were born on the same time (this is the LocalDateTime) but if we align the dates on the timeline (using Instant) we will find out that the one born in California is few hours younger than the one born in the UK (NB: to create the appropriate Instant we have to convert the time to UTC, this is where the difference lays).<...>
In order to get long from Instant you could use getEpochSecond() method.
In order to get long from LocalDateTime you should provide a timezone.

Comparing Dates and adding days to Dates in a comparison [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I am totally out of my depth here. I have this pseudo code that I would like to write in Java but have no idea where to start. The following is the logic that I would like to express. Any advice would be much appreciated.
if(bestBeforeDate <= today() + 2days) // if a product is two days before its best before date
toShipOut = false;
else if (bestBeforeDate >= today >= bbDate- 8 days) // from 8 days before best before day
DiscountedPrice();
else
toShipOut = true;
Use Calendar.add() to add number of days. You need to have a temporary Calendar for each additions.
Calendar c = Calendar.getInstance();
c.setTime(new Date()); // Current date
c.add(Calendar.DATE, 2); // Adding 2 days
Check Out Date.
Notice the constructor Date(int year, int month, int date)
Also notice the boolean method after(Date when)
You should be able to find everything you need there.
GregorionCalendar is usually preferred to Date now, but it is the same concept.
GregorianCalendar(int year, int month, int dayOfMonth)
public int compareTo(Calendar anotherCalendar)
Beware of Date/Calendar Classes
Caution: The java.util.Date/Calendar classes bundled with Java are notoriously bad. Instead, use the third-party library Joda-Time, or in Java 8 use the new JSR 310 features (inspired by Joda-Time).
Considerations
Think about time as well as date. And time zones. Generally it is best to store and work with UTC time (no time zone offset), then convert to zoned date-time for presentation to user.
Example Code
I'm not promising this source code example is logically consistent, but it will put you in the right direction. Joda-Time 2.3 on Java 7 on a Mac.
The boolean logic in your pseudo-code is flawed, so I ignored that aspect. I focused on the date-time angle.
// © 2013 Basil Bourque. This source code may be used freely forever by anyone taking full responsibility for doing so.
// import org.joda.time.*;
DateTimeZone denverTimeZone = DateTimeZone.forID( "America/Denver" );
// In real world, get 'bestBeforeDate' from storage. Stored in UTC.
// Call 'withTimeAtStartOfDay' method rather than try to set midnight. Not every day in every time zone has a midnight.
// For this example, we'll hard-code bestBeforeDate to first moment of day Nov 1 in Denver. Then convert to UTC.
DateTime bestBeforeDate = new DateTime( 2013, DateTimeConstants.NOVEMBER, 1, 3, 3, denverTimeZone ).withTimeAtStartOfDay().toDateTime( DateTimeZone.UTC );
DateTime now = new DateTime().toDateTime( DateTimeZone.UTC );
DateTime twoDaysFromNow = now.plusDays( 2 );
if ( bestBeforeDate.isBefore( twoDaysFromNow ) ) {
// Do something
} else {
// Do something else.
}
System.out.println( "bestBeforeDate: " + bestBeforeDate );
System.out.println( "now: " + now );
System.out.println( "twoDaysFromNow: " + twoDaysFromNow );
When run…
bestBeforeDate: 2013-11-01T06:00:00.000Z
now: 2013-12-03T04:54:55.405Z
twoDaysFromNow: 2013-12-05T04:54:55.405Z

Categories

Resources