The JDK1.8 API saies the result of the Date(long date) is based on the time January 1, 1970, 00:00:00 GMT, but when I test it by set the date=0, I find the result is not the Thu Jan 01 08:00:00 CST 1970, it's not the 00:00:00,but the 08:00:00,why?the result about the Date(long date)
It's because of your timezone.
If you change the time zone to GMT it will show 00:00:00
Date date = new Date(0L);
TimeZone.setDefault(TimeZone.getTimeZone("GMT"));
System.out.println(date);
Output : Thu Jan 01 00:00:00 GMT 1970
tl;dr
Instant.EPOCH.toString()
1970-01-01T00:00:00Z
Instant.EPOCH.atZone( ZoneId.of( "America/Chicago" ) ).toString() // Use proper time zone names (continent/region). Avoid pseudo-zones such as `CST`, which could be Central Standard Time in US or China Standard Time.
1969-12-31T18:00-06:00[America/Chicago]
Instant.EPOCH.atZone( ZoneId.of( "Asia/Hong_Kong" ) ).toString()
1970-01-01T08:00+08:00[Asia/Hong_Kong]
Avoid legacy date-time classes
You are using you using old date-time classes, now legacy, supplanted by the java.time classes.
Among its many problems, the toString method of java.util.Date implicitly applies the JVM’s current default time zone while generating a string. Avoid this class.
java.time
Instead use Instant. Represents a moment on the timeline in UTC with a resolution of nanoseconds.
Instant.ofEpochSecond( 0 ).toString()
1970-01-01T00:00:00Z
Or use the constant for that value, Instant.EPOCH.
For current moment in UTC, call now.
Instant.now()
To adjust into a specific time zone, search Stack Overflow for ZonedDateTime and ZoneId.
Adjust into another time zone. Same moment, same simultaneous point on the time line, but different wall-clock time.
Specify a proper time zone name in the format of continent/region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland. Never use the 3-4 letter abbreviation such as EST or IST as they are not true time zones, not standardized, and not even unique(!).
ZoneId z = ZoneId.of( "Asia/Hong_Kong" ) ;
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.
With a JDBC driver complying with JDBC 4.2 or later, you may exchange java.time objects directly with your database. No need for strings or java.sql.* classes.
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
Later versions of Android bundle implementations of the java.time classes.
For earlier Android, 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.
It is because of the TimeZone set, by default by the JVM when & where you run the program, look at the below statement from the Java doc.
Typically, you get a TimeZone using getDefault which creates a
TimeZone based on the time zone where the program is running. For
example, for a program running in Japan, getDefault creates a TimeZone
object based on Japanese Standard Time.
You can look at here
Related
I am getting time in string like this "2011-02-27T10:03:33.099-06:00" which is of xml dateTime type. I also have timezone of TimeZone type. How should I convert the dateTime to GregorianCalendar java type in that timezone.
Java has built in code to parse xml datetimes: use DatatypeConverter.parseDateTime(). that will return a Calendar in the parsed TimeZone. you can then set the Calendar TimeZone to your desired target TimeZone for whatever you need to do next.
sdf = new java.text.SimpleDateFormat ("yyyy-MM-dd'T'HH:mm:ss.S");
parses everything, except the trailing TZ.
sdf.parse (sd);
res168: java.util.Date = Sun Feb 27 10:03:33 CET 2011
From the api docs, I would expect
sdf = new java.text.SimpleDateFormat ("yyyy-MM-dd'T'HH:mm:ss.SSSz");
to be used to read the -06:00 in the end. But I see, that there is either an offset in the form 0700 expected, or with a prefix of GMT for example "GMT-04:00". So you have to insert that GMT-thingy yourself:
sdf.parse (sd.replaceAll ("(......)$", "GMT$1"))
SDF.parse (str) returns a Date, which has to be converted into a GC:
GregorianCalendar calendar = new GregorianCalendar ();
calendar.setTime (date);
tl;dr
OffsetDateTime.parse( "2011-02-27T10:03:33.099-06:00" )
java.time
The modern approach uses the java.time classes that supplanted the troublesome old legacy date-time classes. Specifically, GregorianCalendar was replaced by ZonedDateTime for a time zone, and OffsetDateTime for a mere offset-from-UTC.
ISO 8601
Your input string happens to comply with the ISO 8601 standard format.
The java.time classes use these standard formats by default when parsing/generating strings. So no need to specify a formatting pattern.
OffsetDateTime
Your input string contains an offset-from-UTC, but not a time zone. So parse as an OffsetDateTime.
OffsetDateTime odt = OffsetDateTime.parse( "2011-02-27T10:03:33.099-06:00" ) ;
ZonedDateTime
If you know for certain the intended time zone, apply a ZoneId to produce a ZonedDateTime.
A time zone is always preferable to a mere offset. A zone is a history of past, present, and future changes to the offset used by the people of a particular region.
Specify a proper time zone name in the format of continent/region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland. Never use the 3-4 letter abbreviation such as EST or IST as they are not true time zones, not standardized, and not even unique(!).
ZoneId z = ZoneId.of( "Pacific/Galapagos" ) ;
ZonedDateTime zdt = odt.atZoneSameInstant( z ) ;
Converting legacy ↔ modern
If you must have a GregorianCalendar object to inter-operate with old code not yet updated to java.time, you can convert. Look to new methods added to the old classes.
GregorianCalendar myGregCal = GregorianCalendar.from( zdt ) ;
And going the other direction…
ZonedDateTime zdt = myGregCal.toZonedDateTime() ;
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.
Using a JDBC driver compliant with JDBC 4.2 or later, you may exchange java.time objects directly with your database. No need for strings nor java.sql.* classes.
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
Later versions of Android bundle implementations of the java.time classes.
For earlier Android, 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 have a POST end-point that takes a couple of values, one being endDate and startDate. When the JSON posts in as:
{ "startDate" : "2015-01-30", "endDate" : "2015-12-30" }
Spring converts it to a java.util.Date Object that is always one day behind. In the logs I see:
Validating that startDate Thu Jan 29 16:00:00 PST 2015 < endDate Tue Dec 29 16:00:00 PST 2015
So it got the timezone correct. I had assumed it was related to UTC conversions, but I'm not sure how to configure this or modify it so that it converts it using the proper off-set. The timestamp portion of it isn't required - I only care that the year, day, and month match what is passed in.
if it matters, I'm using Spring (happened with 4.0.6 and 4.1.7) and a POST
tl;dr
LocalDate.parse( "2015-01-30" )
Use the right data type for the job
You are trying to fit a date-only value into a date-time type, java.util.Date. Square peg, round hole. While trying to come up with a time-of-day to associate with your date, a time zone is being injected, hence your problem.
LocalDate
Solution:
Never use the terrible old legacy date-time classes such as java.util.Date. Use only the modern java.time classes.
For a date-only value, use LocalDate.
Your input string happens to be in standard ISO 8601 format. The java.time classes use ISO 8601 formats by default when parsing/generating strings. So no need to specify a formatting pattern.
LocalDate ld = LocalDate.parse( "2015-01-30" ) ;
ZonedDateTime
If you want a moment, a date with a time-of-day, let java.time determine the first moment of the day. Never assume that moment is 00:00:00. In some zones on some dates it may be another time such as 01:00:00 because of anomalies such as Daylight Saving Time (DST).
ZonedId z = ZoneId.of( "America/Montreal" ) ;
ZonedDateTime zdt = ld.atStartOfDay( z ) ; // Let java.time determine the first moment of that date in that zone.
Instant
To adjust from to UTC (same moment, different wall-clock time), extract an Instant.
Instant instant = zdt.toInstant() ; // Adjust to UTC. Same moment, same simultaneous point on the timeline, different wall-clock 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.
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.
String str="2015-01-30";
try{
SimpleDateFormat isoFormat = new SimpleDateFormat("yyyy-MM-dd");
isoFormat.setTimeZone(TimeZone.getTimeZone("PST"));
Date date = isoFormat.parse(str);
System.out.println(date);
}catch(ParseException e){
e.printStackTrace();
}
Check here http://docs.spring.io/spring/docs/current/spring-framework-reference/html/mvc.html#mvc-ann-webdatabinder how to customize automatic Spring conversion:
#Controller
public class MyFormController {
#InitBinder
public void initBinder(WebDataBinder binder) {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
dateFormat.setLenient(false);
binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, false));
}
// ...
}
I am trying to extract the day of month of today's date. I have this
DateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
Date date = new Date();
JOptionPane.showMessageDialog(null, date.getDay());
but when the message dialog appears it show the number 5
and today it's the 8th. How can I set it to show what day of the month it is?
date.getDay() returns the day of the week. sunday is 0 and similarly saturday is 6.
Please see the java docs
As per the comment given below
Calendar cal = Calendar.getInstance();
int dayOfMonth = cal.get(Calendar.DAY_OF_MONTH);
String dayOfMonthStr = String.valueOf(dayOfMonth);
System.out.println(dayOfMonthStr);
Try this out.
JOptionPane.showMessageDialog(null, date.getTime());
You started to use the SimpleDateFormat class, but didn't do anything with it. Try:
System.out.println( new SimpleDateFormat("EEEE").format( new Date() ) );
System.out.println( new SimpleDateFormat("d").format( new Date() ) );
tl;dr
LocalDate.now() // Capture the current date as seen in the wall-clock time used by the people of a certain region, that region represented by the JVM’s current default time zone.
.getDayOfMonth() // Extract the day-of-month. Returns an `int`.
java.time
extract the day of month of today's date
The modern approach uses the java.time classes that supplant the troublesome old date-time classes bundled with the earliest versions of Java.
LocalDate
The LocalDate class represents a date-only value without time-of-day and without time zone.
A time zone is crucial in determining a date. For any given moment, the date varies around the globe by zone. For example, a few minutes after midnight in Paris France is a new day while still “yesterday” in Montréal Québec.
If no time zone is specified, the JVM implicitly applies its current default time zone. That default may change at any moment, so your results may vary. Better to specify your desired/expected time zone explicitly as an argument.
Specify a proper time zone name in the format of continent/region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland. Never use the 3-4 letter abbreviation such as EST or IST as they are not true time zones, not standardized, and not even unique(!).
ZoneId z = ZoneId.of( "America/Montreal" ) ;
LocalDate today = LocalDate.now( z ) ;
If you want to use the JVM’s current default time zone, ask for it and pass as an argument. If omitted, the JVM’s current default is applied implicitly. Better to be explicit, as the default may be changed at any moment during runtime by any code in any thread of any app within the JVM.
ZoneId z = ZoneId.systemDefault() ; // Get JVM’s current default time zone.
Interrogate the LocalDate for its day-of-month.
int dayOfMonth = today.getDayOfMonth() ;
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.
Joda-Time
UPDATE: The Joda-Time project is now in maintenance mode, with the team advising migration to the java.time classes. I am leaving this section intact as history.
In Joda-Time 2.3 in Java 7…
org.joda.time.DateTime theEighth = new org.joda.time.DateTime( 2013, 11, 8, 18, 0 ); // Default time zone.
System.out.println( "theEighth: " + theEighth );
System.out.println( "dayOfMonth of theEighth: " + theEighth.dayOfMonth().getAsText() );
When run…
theEighth: 2013-11-08T18:00:00.000-08:00
dayOfMonth of theEighth: 8
Hi
I have a date/Time field i want to get Convert current IST to CURRENT PST in java... need help....
ex: now in IST its :13/may/2011 3.32.58pm want the same in PST i.e. 13/may/2011 3.02.58 AM
thank you........
If you're interested in the current time, you don't need to know about IST at all... just the current instance, and the conversion to PST. You can do this with something like:
Date now = new Date();
TimeZone zone = TimeZone.getTimeZone("America/Los_Angeles"); // For example...
DateFormat format = new SimpleDateFormat("..."); // Put your pattern here
format.setTimeZone(zone);
String text = format.format(now);
Personally I'd recommend you use Joda Time for all date/time work instead, as it's a much nicer API - but in this case it's really pretty simple even with the built-in API.
The Answer by Jon Skeet is correct but now outdated with the arrival of the java.time code in Java 8 and later.
java.time
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).
Get current moment in UTC.
Instant instant = Instant.now();
Adjust into a time zone.
Specify a proper time zone name in the format of continent/region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland. Never use the 3-4 letter abbreviation such as EST or IST as they are not true time zones, not standardized, and not even unique(!).
ZoneId z = ZoneId.of( "America/Los_Angeles" );
ZonedDateTime zdt = instant.atZone( z );
To generate a String in standard ISO 8601 format, call the toString. For alternate formatting, use the DateTimeFormatter class already covered in many other Questions and Answers.
String output = zdt.format( myDateTimeFormatter );
See the same moment in India time, specifically Asia/Kolkata.
ZoneId zKolkata = ZoneId.of( "Asia/Kolkata" );
ZonedDateTime zdtKolkata = zdt.withZoneSameInstant( zKolkata );
I am not sure if by IST you meant India Standard Time or Irish Standard Time. Let's cover Europe/Dublin as well. That zone happens to currently use an offset of zero, +00:00. So its wall-clock time in the same as UTC.
ZoneId zDublin = ZoneId.of( "Europe/Dublin" );
ZonedDateTime zdtDublin = zdt.withZoneSameInstant( zDublin );
See this code run live at IdeOne.com.
instant.toString(): 2017-02-13T07:28:57.738Z
zdt.toString(): 2017-02-12T23:28:57.738-08:00[America/Los_Angeles]
zdtKolkata.toString(): 2017-02-13T12:58:57.738+05:30[Asia/Kolkata]
zdtDublin.toString(): 2017-02-13T07:28:57.738Z[Europe/Dublin]
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 and 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 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.
This question already has answers here:
Epoch is not epoch if do a new Date(0L). Why?
(4 answers)
Closed 5 years ago.
The Java doc describe that the constructor Date(long date) constructs a Date object using the given milliseconds time value since January 1, 1970, 00:00:00 GMT
When I did new Date(0), the date is Jan 01 01:00:00 CET 1970
I don't know why it begin with 01h
It's show 1AM because you're an hour ahead of GMT. A date instance is simply a counter of the number of milliseconds since 00:00:00 1970 GMT. Since your an hour ahead, when the epoch occurred it was actually 1AM your time.
The Date instance simply formats its toString() method to use your system's timezone. If you want to print out a date using a different zone, use a DateFormat instance.
This is because you are showing the date in the European timezone (CET) the unix time (the milliseconds you are giving the Date object) use GMT.
tl;dr
Instant.now() // Current moment in UTC.
Details
The Answer by Nichols is correct but outdated.
Your own time zone was an hour ahead of UTC on that date, so midnight in UTC is 1 AM in your zone.
Nowadays you should be using java.time classes such as Instant instead of Date.
Avoid legacy classes
Avoid the troublesome old date-time classes now supplanted by the java.time classes.
Among the many problems of the legacy classes was the poor design choice to have the toString method dynamically apply the JVM’s current default time zone while generating the string representing the object’s value. A Date actually represents a moment in UTC. Avoid awkward class entirely. If necessary, convert between the legacy and modern classes via new methods added to the old classes.
Instant for UTC
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 = Instant.now() ; // Current moment in UTC.
instant.toString(): 2018-02-11T21:07:02.315283Z
If you want the epoch reference moment used by the java.time classes, the first moment of 1970 in UTC, use the predefined constant: Instant.EPOCH.
Instant.EPOCH.toString(): 1970-01-01T00:00:00Z
OffsetDateTime
If you need more flexibility, such as generating strings in other formatting, convert the Instant object to a OffsetDateTime using the constant ZoneOffset.UTC.
OffsetDateTime odt = instant.atOffset( ZoneOffset.UTC ) ;
ISO 8601
When exchanging date-time values as text, use the standard ISO 8601 formats. They were designed to be easy to parse by machine while also being easy to read by humans across various cultures.
The java.time classes use the standard ISO 8601 formats by default when generating/parsing strings. So no need to specify a formatting pattern.
Time zone, ZonedDateTime
If you want to see the same simultaneous moment through the lens of the wall-clock time used by the people of another region, apply a time zone (ZoneId) to get a ZonedDateTime object.
Specify a proper time zone name in the format of continent/region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland. Never use the 3-4 letter abbreviation such as EST or IST or CET as they are not true time zones, not standardized, and not even unique(!).
ZoneId z = ZoneId.of( "Europe/Paris" ) ;
ZonedDateTime zdt = instant.atZone( z ) ;
zdt.toString(): 2018-02-11T22:07:02.315283+01:00[Europe/Paris]
Let's look at the java.time epoch reference moment through the same time zone.
ZonedDateTime zdtEpochParis = Instant.EPOCH.atZone( z ) ;
zdtEpochParis.toString(): 1970-01-01T01:00+01:00[Europe/Paris]
Again, for another time zone.
ZonedDateTime zdtEpochMontreal = Instant.EPOCH.atZone( ZoneId.of( "America/Montreal" ) ) ;
zdtEpochMontreal.toString(): 1969-12-31T19:00-05:00[America/Montreal]
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.
With a JDBC driver complying with JDBC 4.2 or later, you may exchange java.time objects directly with your database. No need for strings or java.sql.* classes.
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
Later versions of Android bundle implementations of the java.time classes.
For earlier Android, 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.