LocalDateTime to Mysql DATETIME converts actual date to actual date+5.30 - java

I am having a model with multiple member variables in that:
One with LocalDateTime type.
#Column(name = "localdatetime_field")
private LocalDateTime updatedAt;
Other with timestamp:
#Column(name = "timestamp_field")
private Timestamp addedAt;
The problem is:
When I save data in the DB, with mysql-connector v8.0.18:
-> It keeps the data of Localdatetime & Timestamp same as given.
with mysql-connector v5.1.34:
-> It changes the data of Localdatetime by +5.30.
I wonder is it because of mysql-connector or some jackson convertor working behind the scenes.

Avoid legacy date-time classes
The java.sql.Timestamp class is obsolete, supplanted years ago by the modern java.time classes defined in JSR 310.
java.time
Not a moment
The LocalDateTime class is appropriate only to database columns of a type akin to the SQL-standard type TIMESTAMP WITHOUT TIME ZONE. These types do not represent a moment, cannot be a point on the timeline. Without the context of a time zone or offset-from-UTC, we cannot know if noon on the 23rd is noon in Tokyo Japan, noon in Toulouse France, or noon in Toledo Ohio US — three different moments, several hours apart.
In the context of most business app, these types are not usually appropriate. If recording when something has happened, these are the wrong types. These types are only good for (a) describing something across all time zones such as when Christmas starts (different moments in various time zones), and (b) booking appointments in the future that should remain at a certain wall-clock time even if politicians change the time zone rules in than region (Ex: dental appointment at 3 PM should stay at 3 PM even if politicians push the clock forward or backward an hour).
A moment
For database columns of a type akin to the SQL-standard type TIMESTAMP WITH TIME ZONE, we would use either Instant, OffsetDateTime, or ZonedDateTime. Oddly, the JDBC 4.2 spec requires support only for the second of those three: OffsetDateTime.
OffsetDateTime odt = myResultSet.getObject( … , OffsetDateTime.class ) ;
Writing to the database:
myPreparedStatement.setObject( … , odt ) ;
If you want to see the returned OffsetDateTime in the time zone of your choice, apply a ZoneId to get a ZonedDateTime. Be sure to use a real time zone name in format of Continent/Region. Never use 2-4 character pseudo-zones such as IST, EST, and such.
ZoneId z = ZoneId.of( "Asia/Kolkata" ) ;
ZonedDateTime zdt = odt.atZoneSameInstant( z ) ;
Beware of middleware
Unfortunately, middleware and tooling often feels the need to inject a time zone adjustment into your date-time info. Most databases store a moment as UTC (an offset from UTC of zero hours-minutes-seconds). Yet some tooling will retrieve that UTC value, apply a time zone adjustment, and then report the result. This anti-feature clouds the picture of what was actually stored in the database.
To get around that anti-feature, you will need to study the documentation for your particular middleware or tool. You may be able to shut off the adjustment. Or as a workaround, you may need to set its applied time zone to be UTC/GMT, or in a pinch use the zone Atlantic/Reykjavik which happens to use zero as its offset.
If doing straight JDBC with the java.time classes, I expect you will see no such rude injection of time zone. At least I have not heard of any such behavior with any JDBC driver yet.
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes. Hibernate 5 & JPA 2.2 support java.time.
Where to obtain the java.time classes?
Java SE 8, Java SE 9, Java SE 10, Java SE 11, and later - Part of the standard Java API with a bundled implementation.
Java 9 brought some minor features and fixes.
Java SE 6 and Java SE 7
Most of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
Later versions of Android (26+) bundle implementations of the java.time classes.
For earlier Android (<26), the process of API desugaring brings a subset of the java.time functionality not originally built into Android.
If the desugaring does not offer what you need, the ThreeTenABP project adapts ThreeTen-Backport (mentioned above) to Android. See How to use ThreeTenABP….

Related

How to update a Timestamp field in MySql from a Java PreparedStatement?

My index.html has an <input type="datetime-local"> field and I need to update a MySql database with whatever value the user selects. My database field is currently a Timestamp. How can I create an update statement that allows me to update the database with this datetime-local value? I've tried many options and my current attempt is shown below; however, this does not work. I am doing this all in Java.
String updateStatement = "UPDATE cars SET reservation = ? WHERE uniqueID = ?";
pStmt = con.prepareStatement(updateStatement);
pStmt.setTimestamp(1, reservation);
pStmt.setTimestamp(2, someUniqueId);
tl;dr
To answer your specific code question (but this is the wrong way to handle appointments/reservations):
myPreparedStatement
.setObject(
1 ,
ZonedDateTime
.of
(
LocalDate.of( 2021 , Month.JANUARY , 23 ) ,
LocalTime.of( 15 , 30 ) ,
ZoneId.of( "Africa/Tunis" )
)
.toInstant()
.atOffset( ZoneOffset.UTC )
)
;
java.time
The TIMESTAMP type in MySQL is for tracking a moment, a specific point on the timeline, as seen from an offset of zero hours-minutes-seconds from UTC, resolving to microseconds. This maps to TIMESTAMP WITH TIME ZONE in standard SQL.
The appropriate match in Java would be java.time.Instant. This class also represents a moment as seen in UTC, but with finer resolution of nanoseconds.
Unfortunately, the JDBC 4.2 specification requires support for only one of the three types that track a moment: OffsetDateTime. Both Instant and ZonedDateTime are optional in JDBC 4.2. So your particular JDBC driver may or may not support Instant. This design decision by the JDBC team baffles me. Converting between Instant and OffsetDateTime is utterly simple, and should have been required by JDBC spec.
I am guessing you are letting users pick a date and a time-of-day within a particular time zone. But I'm not sure, as your neglected to detail your inputs.
LocalDate localDate = LocalDate.of( 2021 , Month.JANUARY , 23 ) ;
LocalTime localTime = LocalTime.of( 15 , 30 ) ;
ZoneId zoneId = ZoneId.of( "America/Edmonton" ) ;
ZonedDateTime zdt = ZonedDateTime.of( localDate, localTime , zoneId ) ;
To store in the database, let's adjust from a time zone to UTC (an offset of zero). Convert from ZonedDateTime to Instant, and then to OffsetDateTime with an offset of zero hours-minutes-seconds represented by the constant ZoneOffset.UTC.
OffsetDateTime odt = zdt.toInstant().atOffset( ZoneOffset.UTC ) ; // Use `OffsetDateTime` rather than `Instant` for maximum compatibility across JDBC 4.2 drivers.
Do not call PreparedStatement#setTimestamp. That method is now legacy, for the terrible java.sql.Timestamp class. Never use date-time classes outside the java.time package. Those legacy classes were supplanted years ago by the modern java.time classes defined in JSR 310.
Call PreparedStatement#setObject. The JDBC team has yet to define specific set… methods for the various java.time classes. Again, a design decision which baffles me. However, we can exchange the java.time objects using setObject/getObject.
myPreparedStatement.setObject( … , odt ) ;
Retrieval.
OffsetDateTime odt = myResultSet.getObject( … , OffsetDateTime.class ) ;
Tracking appointments
By the way, you mentioned the business problem is making restaurant reservations in the future. For this work, you are taking the wrong approach.
Such future appointments are not tracked as moments, are not specific points on the timeline. If politicians were to change the offset used by that time zone, your customers expect a restaurant reservation for 7 PM to stay at 7 PM, regardless of politicians moving the clock forward or backward. Similarly, a dental appointment for 3 PM four months from now should stay at 3 PM even if the politicians change the offset. And politicians around the world do enjoy changing their time zone offset. This happens surprisingly often, and with less and less forewarning.
Reservations/appointments should be tracked as date and time without time zone, storing time zone separately in second column of database. These types would be TIMESTAMP WITHOUT TIME ZONE in standard SQL, and DATETIME in MySQL. And use a text type for the time zone identifier. The matching type in Java would be LocalDateTime and ZoneId. At runtime for calendaring, combine to determine a moment with a ZonedDateTime.
I and other authors have covered this many times already on Stack Overflow. So search to learn more.
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes. Hibernate 5 & JPA 2.2 support java.time.
Where to obtain the java.time classes?
Java SE 8, Java SE 9, Java SE 10, Java SE 11, and later - Part of the standard Java API with a bundled implementation.
Java 9 brought some minor features and fixes.
Java SE 6 and Java SE 7
Most of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
Later versions of Android (26+) bundle implementations of the java.time classes.
For earlier Android (<26), a process known as API desugaring brings a subset of the java.time functionality not originally built into Android.
If the desugaring does not offer what you need, the ThreeTenABP project adapts ThreeTen-Backport (mentioned above) to Android. See How to use ThreeTenABP….
Maybe your date format is incorrect.
reservation = System.currentTimeMillis();
UPDATE
Ok,I understand you.You should use String to receive the datetime-local value.
Because the format of datetime-local from frontend is yyyy-MM-ddTHH:mm, but the format of TimeStamp in Java(package java.sql) is yyyy-MM-ddTHH:mm:ss.
It lack the :ss, so can not receive.
Finally set timestamp after convert String to TimeStamp.
datetimeLocal = datetimeLocal.replaceAll("T", " ") + ":00";
Timestamp reservation = Timestamp.valueOf(datetimeLocal);

Date.from(ZonedDateTime to instant) returning previous day

My variable in java of type ZonedDateTime is say time="2017-01-03T00:00Z[UTZ]" . And when i try to get Date from like this - Date.from(time.toInstance()) it returns previous day i.e Mon Jan 02 19:00:00 EST 2017, I dont know why ? Could anyone shed some light on my it returns previous day ?
Avoid legacy date-time classes
Never use java.util.Date class. That terrible class, along with Calendar & SimpleDateFormat and others are now legacy. The new to/from conversion methods added to the old classes are intended only for use when you are interoperating with old code not yet updated to java.time. Avoid Date whenever possible.
Among the many flaws in Date is its unfortunate behavior of dynamically applying the JVM’s current default time zone while generating the text in its toString method. So it appears a Date has a time zone while actually a Date represents a moment in UTC. In other words, Date::toString lies. One of many reasons to avoid this class.
➥ In the winter of 2017, many of the time zones on the east coast of North America are five hours behind UTC. So midnight in UTC is simultaneously 7 PM (19:00) in New York, Montréal, etc. Same moment, different wall-clock time.
java.time
The Date class was supplanted by Instant years ago.
ZonedDateTime is say time="2017-01-03T00:00Z[UTZ]"
If you are trying to track moments in UTC, use either:
InstantInstant.now()
OffsetDateTime object set to UTC.OffsetDateTime.now( ZoneOffset.UTC )
Use the ZonedDateTime class when you have a moment in the context of a time zone. A time zone is a history of the past, present, and future changes to the offset-from-UTC used by the people of a particular region.
ZonedDateTime.now(
ZoneId.of( "Africa/Tunis" )
)
You can adjust between UTC and a zone. Same moment, different ways to view it, different wall-clock times.
ZonedDateTime zdt = instant.atZone( ZoneId.of( "Pacific/Auckland" ) ) ;
…and…
Instant instant = zdt.toInstant() ;
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.
Where to obtain the java.time classes?
Java SE 8, Java SE 9, Java SE 10, Java SE 11, and later - Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and Java SE 7
Most of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
Later versions of Android bundle implementations of the java.time classes.
For earlier Android (<26), the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.
ZonedDateTime.toInstant() adjusts a moment from a time zone to UTC. You end up with the same moment, different wall-clock time, and possibly a different date for the same simultaneous point on the timeline. What you are seeing is not a problem, not a discrepancy.
Classes like LocalDate and ZonedDateTime provide a human view on time.
However, often we need to work with time viewed from a machine perspective.
For this, we can use the Instant class which represents timestamps.
An Instant counts the time beginning from the first second of January 1, 1970 (1970-01-01 00:00:00) also called the EPOCH.
Instant values can be negative if they occurred before the epoch. They followISO 8601 the standard for representing date and time.
Also, use the Java Time API libraries introduced in Java 8 as there were many issues in the existing Date and Calendar APIs Please
refer: https://www.baeldung.com/java-8-date-time-intro

convert a unix timestamp to a postgres equivalent timestamp in java

I have a field in postgres
Column | Type
created_at | timestamp without time zone
I have a unix timestamp stored in long in Java
long createdAtTime = data.getcreatedAtTime();
I want to convert it to timestamp in java so that I can store with activejdbc into postgres
I tried the following
Date convertedTime = new Date(createdAtTime*1000L);
record.set("created_at", convertedTime);
record.saveIt();
But I get the following error:
Can't infer the SQL type to use for an instance of java.util.Date. Use setObject() with an explicit Types value to specify the type to use.
Should I be using a different way to convert the date first?
java.sql.Timestamp timestamp = new Timestamp(createdAtTime*1000L);
record.set("created_at", convertedTime);
record.saveIt();
Instead of util you have tried with java.sql.Date.
Its a native type of SQL.
Incompatible types
I have a field in postgres …
timestamp without time zone …
…and…
I have a unix timestamp stored in long in Java
long createdAtTime = data.getcreatedAtTime();
This is a contradiction.
The SQL-standard type TIMESTAMP WITHOUT TIME ZONE purposely lacks any indicator of time zone or offset-from-UTC. As such, this type does not represent a moment, is not a point on the timeline. This type represents potential moments along a range of about 26-27 hours, the range of time zones around the globe.
If you are trying to track specific moments, use the other SQL-standard type, TIMESTAMP WITH TIME ZONE. In Postgres, all values of this type are stored in UTC (an offset of zero). If you pass a value indicating some other offset or time zone, Postgres adjusts the value to UTC before storing.
When retrieving a value from a column of type TIMESTAMP WITH TIME ZONE in Postgres, you are always getting a value in UTC. Unfortunately, some well-intentioned tools or drivers sitting between you and the database may decide the dynamically apply a time zone to the value. While well-intentioned, I consider this quite the anti-feature. This behavior creates the illusion of a time zone stored in the database while in fact Postgres only stores UTC in this type.
Date convertedTime = new Date(createdAtTime*1000L);
The java.util.Date class is terrible, poorly designed and flawed. Never use this class nor its siblings, Calendar, SimpleDateFormat, and such. These are all legacy now, supplanted years ago by the modern java.time classes defined in JSR 310.
Instant
The Instant class takes over for java.util.Date. Both classes represent a moment in UTC, though Instant has a finer resolution of nanoseconds versus milliseconds.
unix timestamp stored in long in Java
If you have a count of whole seconds from the epoch reference of the first moment of 1970 in UTC, 1970-01-01T00:00:00Z, convert to an Instant.
Instant instant = Instant.ofEpochSecond( 1_539_555_140L ) ;
Tip: Do not make a habit of tracking time as a count-from-epoch. This is ambiguous (different systems use different resolutions and different epoch references), error-prone, and makes debugging/logging treacherous. Use java.time objects and standard ISO 8601 strings for representing date-time values.
Your JDBC driver may be able to accept an Instant.
myPreparedStatement.setObject( … , instant ) ;
Retrieval:
Instant instant = myResultSet.getObject( … , Instant.class ) ;
OffsetDateTime
If not supporting Instant, use convert to OffsetDateTime. Any JDBC 4.2 or later driver is required to support OffsetDateTime.
OffsetDateTime represents a date and time-of-day with an offset-from-UTC. In contrast, Instant is fixed at UTC, serving as a basic building-block class in java.time framework. Also, OffsetDateTime is more flexible with abilities such as generating strings in various formats versus Instant using only standard ISO 8601 format.
OffsetDateTime odt = instant.atOffset( ZoneOffset.UTC ) ;
myPreparedStatement.setObject( … , odt ) ;
Retrieval:
OffsetDateTime odt = myResultSet.getObject( … , OffsetDateTime.class ) ;
…or…
Instant instant = myResultSet.getObject( … , OffsetDateTime.class ).toInstant() ;
LocalDateTime
If you are not trying to represent moments, such as database type TIMESTAMP WITHOUT TIME ZONE, use the LocalDateTime class.
But if you are thinking use of these types is somehow avoiding the work of using time zones in tracking moments, you are sorely mistaken. This is a “pay now or pay later” situation: Either learn basic date-time concepts and handling practice now, or desperately wrestle with a horrible mess of failed data later.
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.
Where to obtain the java.time classes?
Java SE 8, Java SE 9, Java SE 10, Java SE 11, and later - Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and Java SE 7
Most of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
Later versions of Android bundle implementations of the java.time classes.
For earlier Android (<26), the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.
I see that your Database column stores value as time stamp without time zone,
why don't you try this
Timestamp current = Timestamp.from(Instant.now());
record.set("created_at", current);//I don't know if you might need to parse
record.saveIt();

How to convert Joda DateTime to UTC MySql timestamp

I have a Joda DateTime object representing a UTC time, and wish to store it in a Timestamp field in a MySql table.
I have the following code:
String ztime = "2013-10-07T08:00:00Z";
DateTimeFormatter parser = ISODateTimeFormat.dateTimeParser();
DateTime dt = parser.parseDateTime(ztime).withZone(DateTimeZone.UTC);
PreparedStatement stmt = con.prepareStatement("insert into time_test (time) values (?)");
stmt.setTimestamp(1, Timestamp(dt.getMillis()));
stmt.execute();
However, when I look in the database, the time that gets store is out by the difference of my database's timezone from UTC.
e.g. when my database is running in UTC+1, and run the above code to save "08:00Z", in the database the Timestamp shows as 09:00.
DateTime's getMillis method says " Gets the milliseconds of the datetime instant from the Java epoch of 1970-01-01T00:00:00Z."
and MySql's Timestamp says: "MySQL converts TIMESTAMP values from the current time zone to UTC for storage, and back from UTC to the current time zone for retrieval.",
so I presume it's the MySql conversion that's causing the issue, because the millis it's being initialized with is relative to a fixed UTC time, so it has no need to convert from current time zone to UTC.
My code to read the data back out into a DateTime works fine, and I get the value out that I put in, but I also need this to work with some 3rd-party code over which
I have no control, which expects the Timestamp to be in the correct UTC time.
How do I get the Timestamp field in the database to match my original UTC date/time ?
tl;dr
Use java.time classes that supplant Joda-Time.
myPreparedStatement.setObject(
… ,
Instant.parse( "2013-10-07T08:00:00Z" )
)
Retrieve.
myResultSet.getObject(
… ,
Instant.class
)
java.time
The Joda-Time project is now in maintenance-mode, recommending migration to its successor, the java.time classes built into Java 8 and later. Both are led by the same man, Stephen Colebourne. You'll find many of the same concepts in play, so fairly easy to migrate.
The Instant class represents a moment on the timeline in UTC with a resolution of nanoseconds (up to nine (9) digits of a decimal fraction).
Your input string happens to be in standard ISO 8601 format. The java.time classes use these standard formats by default when parsing/generating strings. So no need to specify a formatting pattern.
String input = "2013-10-07T08:00:00Z" ; // Standard ISO 8601 format.
Instant instant = Instant.parse( input ) ; // Parses standard ISO 8601 format by default.
The Instant class replaces both java.util.Date and java.sql.Timestamp. As of JDBC 4.2 and later, you can directly exchange java.time objects with the database.
myPreparedStatement.setObject( … , instant ) ;
And retrieval.
Instant instant = myResultSet.getObject( … , Instant.class ) ;
The TIMESTAMP type in MySQL seems to be akin to the SQL-standard TIMESTAMP WITH TIME ZONE type. So the code above should work appropriately.
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.
Where to obtain the java.time classes?
Java SE 8, Java SE 9, Java SE 10, and later
Built-in.
Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and Java SE 7
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
Later versions of Android bundle implementations of the java.time classes.
For earlier Android (<26), the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

Determine Whether Daylight Savings Time (DST) is Active in Java for a Specified Date

I have a Java class that takes in the latitude/longitude of a location and returns the GMT offset when daylight savings time is on and off. I am looking for an easy way to determine in Java if the current date is in daylight savings time so I can apply the correct offset. Currently I am only performing this calculation for U.S. timezones although eventually I would like to expand this to global timezones as well.
This is the answer for the machine on which the question is being asked:
TimeZone.getDefault().inDaylightTime( new Date() );
A server trying to figure this out for a client will need the client's time zone. See #Powerlord answer for the reason why.
For any particular TimeZone
TimeZone.getTimeZone( "US/Alaska").inDaylightTime( new Date() );
tl;dr
ZoneId.of( "America/Montreal" ) // Represent a specific time zone, the history of past, present, and future changes to the offset-from-UTC used by the people of a certain region.
.getRules() // Obtain the list of those changes in offset.
.isDaylightSavings( // See if the people of this region are observing Daylight Saving Time at a specific moment.
Instant.now() // Specify the moment. Here we capture the current moment at runtime.
) // Returns a boolean.
java.time
Here is the modern java.time (see Tutorial) version of the correct Answer by mamboking.
A ZoneId represents a time zone. The class knows the rules that tell if DST applies to a particular time zone.
The ZoneRules class models all the historic and future transitions for a time-zone.
An Instant is a moment on the timeline in UTC.
A ZonedDateTime is the result of applying a ZoneId to an Instant.
Example code:
ZonedDateTime now = ZonedDateTime.now( ZoneId.of( "America/Montreal" ) );
…
ZoneId z = now.getZone();
ZoneRules zoneRules = z.getRules();
Boolean isDst = zoneRules.isDaylightSavings( now.toInstant() );
Note how in the last line we had to extract an Instant object from our ZonedDateTime object with a simple call to toInstant.
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.
Where to obtain the java.time classes?
Java SE 8, Java SE 9, Java SE 10, Java SE 11, and later - Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and Java SE 7
Most of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
Later versions of Android bundle implementations of the java.time classes.
For earlier Android (<26), the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.
TimeZone tz = TimeZone.getTimeZone("EST");
boolean inDs = tz.inDaylightTime(new Date());
You're going to have to do a bit more work using those coordinates and figure out which time zone they're in. Once you know which TimeZone that is, the isDayLight() method would be useful.
For example, you have no way of telling whether -0500 is EST (US/Canada Eastern Standard Time), CDT (US/Canada Central Daylight Time), COT (Colombia Time), AST (Brazil Acre Standard Time), ECT (Ecuador Time), etc...
Some of these may or may not support daylight saving time.
Joda Time contains handling methods which will calculate the offsets for you. See DateTimeZone.convertLocalToUTC(...)
To supplement this, you will need to look up the current time zone with your latitude/longitude info. GeoNames provides a java client for its web service, as well as a simple web-request framework (i.e. http://ws.geonames.org/timezone?lat=47.01&lng=10.2)

Categories