I am getting the following exception while trying to convert java.util.Date to java.time.LocalDate.
java.time.DateTimeException: Unable to obtain ZonedDateTime from TemporalAccessor: 2014-08-19T05:28:16.768Z of type java.time.Instant
The code is as follow:
public static Date getNearestQuarterStartDate(Date calculateFromDate){
int[] quaterStartMonths={1,4,7,10};
Date startDate=null;
ZonedDateTime d=ZonedDateTime.from(calculateFromDate.toInstant());
int frmDateMonth=d.getMonth().getValue();
Is there something wrong in the way I am using the ZonedDateTime class?
As per documentation, this should convert a java.util.Date object to ZonedDateTime. The date format above is standard Date?
Do I have to fallback on Joda time?
If someone could provide some suggestion, it would be great.
To transform an Instant to a ZonedDateTime, ZonedDateTime offers the method ZonedDateTime.ofInstant(Instant, ZoneId). So
So, assuming you want a ZonedDateTime in the default timezone, your code should be
ZonedDateTime d = ZonedDateTime.ofInstant(calculateFromDate.toInstant(),
ZoneId.systemDefault());
To obtain a ZonedDateTime from a Date you can use:
calculateFromDate.toInstant().atZone(ZoneId.systemDefault())
You can then call the toLocalDate method if you need a LocalDate. See also: Convert java.util.Date to java.time.LocalDate
The Answer by assylias and the Answer by JB Nizet are both correct:
Call the new conversion method added to the legacy class, java.util.Date::toInstant.
Call Instant::atZone, passing a ZoneId, resulting in a ZonedDateTime.
But your code example is aimed at quarters. For that, read on.
Quarters
No need to roll-your-own handling of quarters. Use a class already written and tested.
org.threeten.extra.YearQuarter
The java.time classes are extended by the ThreeTen-Extra project. Among the many handy classes provided in that library you will find Quarter and YearQuarter.
First get your ZonedDateTime.
ZonedId z = ZoneID.of( "Africa/Tunis" ) ;
ZonedDateTime zdt = myJavaUtilDate.toInstant().atZone( z ) ;
Determine the year-quarter for that particular date.
YearQuarter yq = YearQuarter.from( zdt ) ;
Next we need the start date of that quarter.
LocalDate quarterStart = yq.atDay( 1 ) ;
While I do not necessarily recommend doing so, you could use a single line of code rather than implement a method.
LocalDate quarterStart = // Represent a date-only, without time-of-day and without time zone.
YearQuarter // Represent a specific quarter using the ThreeTen-Extra class `org.threeten.extra.YearQuarter`.
.from( // Given a moment, determine its year-quarter.
myJavaUtilDate // Terrible legacy class `java.util.Date` represents a moment in UTC as a count of milliseconds since the epoch of 1970-01-01T00:00:00Z. Avoid using this class if at all possible.
.toInstant() // New method on old class to convert from legacy to modern. `Instant` represents a moment in UTC as a count of nanoseconds since the epoch of 1970-01-01T00:00:00Z.
.atZone( // Adjust from UTC to the wall-clock time used by the people of a particular region (a time zone). Same moment, same point on the timeline, different wall-clock time.
ZoneID.of( "Africa/Tunis" ) // Specify a time zone using proper `Continent/Region` format. Never use 2-4 letter pseudo-zone such as `PST` or `EST` or `IST`.
) // Returns a `ZonedDateTime` object.
) // Returns a `YearQuarter` object.
.atDay( 1 ) // Returns a `LocalDate` object, the first day of the quarter.
;
By the way, if you can phase out your use of java.util.Date altogether, do so. It is a terrible class, along with its siblings such as Calendar. Use Date only where you must, when you are interfacing with old code not yet updated to java.time.
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.
The answer didn't work for me on Java 10 storing util.Date in UTC.
Date.toInstant() seems to convert the EpochMillis into the local time zone of the server.
ZDT.ofInstant(instant, zoneId) and instant.atZone(zoneId) seem to just tag on a TZ on the instant, but it's already messed up with.
I couldn't find a way to prevent Date.toInstant() from messing with the UTC time with the system time zone.
The only way I found to work around this was to go through the sql.Timestamp class:
new java.sql.Timestamp(date.getTime()).toLocalDateTime()
.atZone(ZoneId.of("UTC"))
.withZoneSameInstant(desiredTZ)
Related
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
This should be quite simple
customerSearch.get("DateOfBirth") where customerSearch is a HashMap<String, Object> and it's a Gregorian Date.
But I need a normal Date object.
I tried
Date dateOfBirth = new Date(
((GregorianCalendar) customerSearch.get("DateOfBirth")).getTimeInMillis());
but said Gregorian Date cannot be cast to Date.
Any help?
tl;dr
( (GregorianCalendar) customerSearch.get( "DateOfBirth" ) ) // Retrieve and cast object of legacy class `GregorianCalendar`.
.toZonedDateTime() // Convert from terrible legacy class to modern *java.time* class.
.toLocalDate() // Extract the date-only portion, omitting time-of-day and time zone.
java.time
You are using, and possibly abusing, terrible date-time classes that were supplanted years ago by the java.time classes defined by JSR 310.
ZonedDateTime replaces GregorianCalendar
Instant replaces java.util.Date
LocalDate replaces java.sql.Date
If you must interoperate with old code not yet updated to java.time, you can convert back-and-forth. Call new conversion methods added to the old classes.
GregorianCalendar gc = customerSearch… ;
ZonedDateTime zdt = gt.toZonedDateTime() ;
If you want just the date without the time-of-day and without the time zone, extract a LocalDate.
LocalDate dateOfBirth = zdt.toLocalDate() ;
If by Date you meant, java.sql.Date class, the above line should be used instead making use of LocalDate.
If by Date you meant java.util.Date, that would be the wrong class to use there. That class represents a moment in UTC. By adjusting from the zoned moment in GregorianCalendar/ZonedDateTime to UTC, you could be changing the date.
Converting
If you need a java.util.Date object to interoperate with old code not yet updated for java.time, you can convert. A java.util.Date represents a moment in UTC, so we need the equivalent in java.time, Instant, also a moment in UTC but with a finer resolution of nanoseconds rather than milliseconds.
We can extract an Instant from our ZonedDateTime seen above. Effectively, this is simply adjusting from a zoned value to a UTC value. Same moment, same point on the timeline, different wall-clock time.
Instant instant = zdt.toInstant() ; // Extract a `Instant`, adjusting from zone to UTC.
Use new conversion methods on the old class.
java.util.Date myJavaUtilDate = java.util.Date.from( instant ) ; // Beware of possible data-loss in the fractional second, truncating from nanos to millis.
If you need go the other direction, from legacy to modern.
Instant instant = myJavaUtilDate.toInstant() ;
Use appropriate types
If you are trying to represent a date-of-birth is is commonly done, with just a date without time-of-day and without zone, then use LocalDate in your map. The classes GregorianCalendar, java.util.Date, and ZonedDateTime all represent a moment, a specific point on the timeline. They should never be used for a date-only.
The java.sql.Date class pretends to be a date-only, but through a terrible design decision as a subclass of java.util.Date actually does indeed carry a time-of-day and offset/zone. This class, as noted above, has been replaced with LocalDate.
normal Date object
There is nothing more “normal” about either java.util.Date or java.sql.Date than any other date-time class.
java.util.Date represents a moment in UTC, always UTC, despite what its terribly designed toString method tells you (a lie). Use java.time.Instant instead when you need a moment in UTC.
java.sql.Date is meant to represent a date-only, but as discussed, actually carries internally a time and zone/offset. Use java.time.LocalDate instead to represent a date rather than a moment.
GregorianCalendar represents a moment as seen in the wall-clock time used by the people of a specific region (a time zone). Instead use ZonedDateTime for this purpose.
java.sql.Timestamp represents a moment in UTC but with a finer resolution of nanoseconds rather than milliseconds. All the moment-related classes in java.time use a resolution of nanoseconds. So for a moment in UTC with a resolution of UTC, use java.time.Instant instead of Timestamp.
As of JDBC 4.2, we can directly exchange java.time classes with a database. So no need to ever touch java.sql.Date or java.sql.Timestamp again for your database work.
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.
There is no java class GregorianDate. Unless it is your own class which if so you didn't mention. So, just in case is Gregorian Date just a regular Date as most of the world today uses Gregorian calendar? So instances of what class does your map holds in your HashMap<String, Object>? If it is just a regular Date then your code should be just:
Date dateOfBirth = (Date)(customerSearch.get("DateOfBirth"));
I'm trying to parse an offset time using Java 8 DateTimeFormatter.
I live in EST time which is UTC-5, so when I try to convert
2019-01-22T13:09:54.620-05:00 should be --> 2019-01-22T18:09:54.620
However, with my code, it gets the current time and goes back 5 hours, resulting in 2019-01-22 08:09:54.620
Code:
import java.sql.Timestamp
import java.time._
import java.time.format.DateTimeFormatter
import scala.util.{Failure, Success, Try}
class MyTimeFormatter(parser: DateTimeFormatter) {
def parse(input: String): Try[Timestamp] = {
Try(new Timestamp(Instant.from(parser.withZone(ZoneOffset.UTC).parse(input)).toEpochMilli))
}
}
Test:
new MyTimeFormatter(DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSxxx")).parse("2019-01-22T13:09:54.620-05:00") shouldEqual Timestamp.valueOf("2019-01-22T18:09:54.620")
where parser is of type DateTimeFormatter and input string is just "2019-01-22T13:09:54.620-05:00"
I want to use this parser.parse method and not with specific temporalAccessors like OffsetDateTime.parse(input, parser) so I can handle all cases like LocalTime, LocalDateTime, ZonedDateTime, OffsetDateTime, etc..
It seems like the code just grabs the time, subtracts the offset, and brands it as UTC instead of calculating the offset with respect to UTC.
Also, is there a way to apply this UTC conversion only if the input format is of ZonedDateTime/OffsetDateTime format? If I input a LocalDateTime (which doesn't have an offset) such as 2017-01-01 12:45:00 the parser will still apply the UTC offset conversion because I told the parser to parse with zone UTC.
tl;dr
Use modern java.time classes. Convert to legacy class only if necessary to work with old code.
Specifically, parse your input string as a OffsetDateTime object, adjust to UTC by extracting an Instant, and lastly, convert to java.sql.Timestamp (only if you must).
java.sql.Timestamp ts = // Avoid using this badly-designed legacy class if at all possible.
Timestamp // You can convert back-and-forth between legacy and modern classes.
.from( // New method added to legacy class to convert from modern class.
OffsetDateTime // Represents a moment with an offset-of-UTC, a number of some hours-minutes-seconds ahead or behind UTC.
.parse( "2019-01-22T13:09:54.620-05:00" ) // Text in standard ISO 8601 format can be parsed by default, without a formatting pattern.
.toInstant() // Adjust from an offset to UTC (an offset of zero) by extracting an `Instant`.
) // Returns a `Timestamp` object. Same moment as both the `OffsetDateTime` and `Instant` objects.
;
See this code run live at IdeOne.com, resulting in:
ts.toString(): 2019-01-22 18:09:54.62
If using JDBC 4.2 or later, skip the Timestamp altogether.
myPreparedStatement.setObject( … , myOffsetDateTime ) ;
Zulu
2019-01-22T13:09:54.620-05:00 should be --> 2019-01-22T18:09:54.620
If you meant that second value to represent a moment in UTC, append the offset-from-UTC to indicate that fact. Either +00:00 or Z (pronounced “Zulu”): 2019-01-22T18:09:54.620Z.
Reporting a moment without an offset-from-UTC or time zone indicator is like reporting an amount of money without a currency indicator.
OffsetDateTime
A string with an offset-from-UTC should be parsed as a OffsetDateTime object.
Your input string happens to comply with the ISO 8601 standard formats for textual date-time values. The java.time classes use ISO 8601 formats by default when parsing/generating strings. So no need to specify a formatting pattern.
OffsetDateTime odt = OffsetDateTime.parse( "2019-01-22T13:09:54.620-05:00" ) ;
Timestamp
Apparently you want a java.sql.Timestamp object. This is one of the terrible date-time classes bundled with the earliest versions of Java. These classes are now legacy, supplanted entirely by the modern java.time classes with the adoption of JSR 310. Avoid these legacy classes whenever possible.
If you must have a Timestamp to interoperate with old code not yet updated to work with java.time, you can convert. To convert, call new methods added to the old classes.
Instant
The java.sql.Timestamp class carries a from( Instant ) method. An Instant is a moment in UTC. To adjust from the offset of our OffsetDateTime to UTC, just extract an Instant.
Instant instant = odt.toInstant() ;
java.sql.Timestamp ts = Timestamp.from( instant ) ;
We have three objects ( odt, instant, & ts ) that all represent the same moment. The first has a different wall-clock time. But all three are the same simultaneous point on the timeline.
JDBC 4.2
As of JDBC 4.2, we can directly exchange java.time objects with the database. So no need to use Timestamp.
myPreparedStatement.setObject( … , odt ) ;
…and…
OffsetDateTime odt = myResultSet.getObject( … , OffsetDateTime.class ) ;
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.
While I cannot reproduce your issue precisely (even with changing my clock to EST), this is what I am observing:
Instant instant = Instant.from(parser.withZone(ZoneOffset.UTC).parse("2019-01-22T13:09:54.620-05:00"));
This is producing the time you would expect (2019-01-22T18:09:54.620Z).
Timestamp ts = new Timestamp(instant.toEpochMilli());
Because this is based on java.util.Date, which displays as your local time.
A better way to convert an Instant to a Timestamp is via the LocalDateTime, like so:
Timestamp ts = Timestamp.valueOf(instant.atZone(ZoneOffset.UTC).toLocalDateTime());
I am trying to save a java.util.Date from an application to my SQL Server database using JDBC.
When I convert the java.util.Date to a java.sql.Date using the method below, it truncates the time part.
java.sql.Date javaSqlExpiryDate = new java.sql.Date(javaUtilExpiryDate.getTime());
System.out.println("javaUtilExpiryDate: " + javaUtilExpiryDate.toString());
System.out.println("javaSqlExpiryDate: " + javaSqlExpiryDate.toString());
The Console window reports the output as:
javaUtilExpiryDate: Thu Sep 01 18:19:08 IST 2016
javaSqlExpiryDate: 2016-09-01
How do I get it to retain the time part as well?
Yes, that's the expected and documented behavior.
Quote from the JavaDocs
To conform with the definition of SQL DATE, the millisecond values wrapped by a java.sql.Date instance must be 'normalized' by setting the hours, minutes, seconds, and milliseconds to zero in the particular time zone with which the instance is associated.
If you want to keep the time, you need to use java.sql.Timestamp (especially if the column in the database is defined as datetime).
Just change your import from java.sql.Date TO java.sql.Timestamp
tl;dr
myPreparedObject.setObject(
1 ,
myJavaUtilDate.toInstant() // Convert legacy object to modern java.time object, `Instant`.
)
Details
The other Answers are correct. The java.util.Date class represents a date and a time-of-day in UTC. The java.sql.Date represents only a date, without the time-of-day. Well, actually, the java.sql.Date pretends to represent only a date but actually, as a badly-designed hack, subclasses the java.util.Date class and therefore does have a time-of-day. Confusing? Yes. One of many reasons to avoid these awful old legacy classes.
Now we have a better way, the java.time classes.
java.time
In the old days you would convert your java.util.Date object to a java.sql.Timestamp.
Now, with a JDBC driver supporting JDBC 4.2 and later, you can send your java.time objects directly to/from the database. No need for either the java.util nor java.sql classes, just stick with java.time classes.
If you have to interface with old code using java.util.Date, convert to java.time.Instant using new methods added to the old classes.
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).
Instant instant = myJavaUtilDate.toInstant() ;
Exchange an Instant with the database via PreparedStatement::setObject and ResultSet::getObject.
myPreparedStatement.setObject( … , instant ) ;
And…
Instant instant = myResultSet.getObject( … , Instant.class ) ;
To see this moment through some other time zone than UTC, apply a ZoneId to get a ZonedDateTime.
ZoneId z = ZoneId.of( "America/Montreal" ) ;
ZonedDateTime zdt = instant.atZone( z ) ;
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.
Where to obtain the java.time classes?
Java SE 8, Java SE 9, 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
The ThreeTenABP project adapts ThreeTen-Backport (mentioned above) for Android specifically.
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 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)