What I mean is this. Suppose I have a date object that is May 1, 2018, 12:00AM. I would like to create a ZonedDateTime object that is May 1, 2018, 12:00AM but of ANOTHER time zone (say EST). Because if I pass in that date object into ZonedDateTime, it treats that date object as UTC (so it treats it as May 1 2018, 12:00AM GMT), and I want it to preserve that date field values but change the timzeone to EST (May 1st 2018, 12:00AM EST). Is there a way to do this in Java?
What you need is a LocalDate:
LocalDate date = LocalDate.of(2018, Month.MAY, 1);
This will be understood in all time zones and will never be anything else than May 1. The “Local” in this and other class names in java.time means “without timezone”.
If you do insist on a ZonedDateTime, the answer is withZoneSameLocal:
ZonedDateTime zdt = date.atStartOfDay(ZoneOffset.UTC);
ZonedDateTime inEst = zdt.withZoneSameLocal(ZoneId.of("Australia/Brisbane"));
System.out.println(inEst);
Output:
2018-05-01T00:00+10:00[Australia/Brisbane]
Don’t rely on EST or other three and four letter time zone abbreviations. EST, for example, is ambiguous (used both in North America and Australia) and is not a time zone (used less than half of the year). Instead give region/city, for example America/Atikokan.
If by “a date object” you meant an object of the outdated java.util.Date class (avoid them if you can, prefer the modern classes in java.time):
Date oldfashionedDate = // …;
OffsetDateTime dateTime = oldfashionedDate.toInstant().atOffset(ZoneOffset.UTC);
if (! dateTime.toLocalTime().equals(LocalTime.MIDNIGHT)) {
throw new IllegalStateException("java.util.Date was supposed to be at midnight in UTC but was " + dateTime);
}
LocalDate date = dateTime.toLocalDate();
System.out.println(date);
Output:
2018-05-01
Related
I have a date format stored in DB, for example:
Thu Aug 27 2020 00:00:00 GMT-0400 (Eastern Daylight Time)
I want to display the same date as output. Seems like I am missing something zone. It's evolving to be one day prior to this date.
I did the following:
DateTimeFormatter etFormat = DateTimeFormatter.ofPattern("MM/dd/yyyy 'at' hh:mma 'ET'");
ZoneId zoneId = ZoneId.of("America/New_York");
ZonedDateTime zonedDateTime = ((Timestamp) date).toLocalDateTime().atZone(zoneId);
etFormat.format(zonedDateTime)
Output:
08/26/2020 at 08:00PM ET
What am I doing wrong?
In your database you have the date time with offset UTC-04:40 (which is 4 hr behind from UTC assuming America/New_York timezone). And when it converts into Timestamp it will be stores in UTC without offset which is 08/26/2020 at 08:00PM.
So first convert the Timestamp into Instant of UTC and then convert the Instant into ZonedDateTime with the zone information
ZonedDateTime dateTime = timestamp.toInstant()
.atZone(ZoneOffset.UTC)
.withZoneSameInstant(ZoneId.of("America/New_York"));
etFormat.format(dateTime); //08/27/2020 at 00:00PM ET
The central issue is this:
java.sql.Timestamp, which is what e.g. resultSet.getTimestamp() returns, does not contain any timezone data. It is simply an instant in time, and it is stored as milliseconds since the epoch (jan 1st, 1970), UTC zone.
This does not match what most DBs store, because most DBs do in fact explicitly store the timezone with that. If your DB does not do this, or you picked a column type which does not do this, you should strongly consider changing that.
So, if the database has stored 'midnight in new york, aug 27th', and the database is forced by JDBC to put this in java.sql.Timestamp terms, there's nothing the DB engine can do about it, other than do its best, which is to return that exact time, in UTC terms. If you then print the UTC timestamp in human terms, you end up with '4 at night', and not 'midnight' (because new york is 4 hours earlier than UTC).
You then, with your code say: Okay, take the timestamp, turn it into a local date time (that'd be the notion of '27th of august, 4 o clock at night', without any inkling of in which czone that is in, and by itself not a thing that can ever be turned back into an epoch with more info), and then you put this at the new york zone, giving you '4 at night in new york', which is 4 hours later than where we started.
Okay, but how do I fix this?
Every other answer (so far) is just giving you silly ways to fight the symptoms.
I propose you fix the disease.
The actual error occurs when you ask the DB to transfer the fully timezoned information from its tables into the timezoneless java.sql.Timestamp object. Stop doing that.
Don't call (I assume your column is called 'mark', fill in whatever it might be):
resultSet.getTimestamp("mark").
Call:
resultSet.getObject("mark", ZonedDateTime.class);
or possibly try LocalDateTime.class, or possibly OffsetDateTime.class, but ZDT is preferred.
Then if that does not work, complain to your DB and/or JDBC driver because they're messing up and making it next to impossible to do timezone stuff properly when interacting with that DB from the java side.
Actually, the DB should store just a moment-in-time
If truly the time being stored represents the notion of an 'instant in time' and not so much 'as humans would ever talk to you about it', then there are data types for that too, but convert your java.sql.Timestamp object to a java.time.Instant asap (via .toInstant()), or straight up ask for it: resultSet.getObject("colName", Instant.class) and have java and the db line up the datatypes straight away.
Eh, whatever. Cures are for wussies, just work around it
Eh, well, the only thing you really need to do then is not to magically add 4 hours. This will do it:
ZonedDateTime dateTime = timestamp.toInstant()
.atZone(ZoneOffset.UTC)
.withZoneSameInstant(ZoneId.of("America/New_York"));
even if the tz stored in the DB is something else (it'll then give you that instant in time, but in new york, e.g. if the db has stored 'midnight in amsterdam', this will give you a time 6 hours earlier (or possibly 7 or 5, there are a few days in the year where things go ape due to US and europe having different shift days for daylight savings).
The format that you have used is not correct. I hope you will be able to understand the difference by comparing your pattern with mine. The reason why I've presented the parsing logic is that you have not made it clear the type of date-time. Whatever type it may be, it looks like you have a date-time string, Thu Aug 27 2020 00:00:00 GMT-0400 (Eastern Daylight Time) which you want to parse into ZonedDateTime and display the same into the pattern of the date-time string you have. I guess, the main problem you are having is how to format the ZonedDateTime instance into the same form.
Do it as follows:
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeFormatterBuilder;
import java.time.format.TextStyle;
public class Main {
public static void main(String[] args) {
// Given date-time string
String dateStr = "Thu Aug 27 2020 00:00:00 GMT-0400 (Eastern Daylight Time)";
// Define the formatter for parsing
DateTimeFormatter parsingFormat = new DateTimeFormatterBuilder()
.appendPattern("EEE MMM dd uuuu HH:mm:ss zX")
.appendLiteral(" (")
.appendGenericZoneText(TextStyle.FULL)
.appendLiteral(")")
.toFormatter();
// Parse the given date-time into ZonedDateTime
ZonedDateTime zonedDateTime = ZonedDateTime.parse(dateStr, parsingFormat);
// Display in default format [i.e. zonedDateTime.toString()]
System.out.println(zonedDateTime);
// Define the formatter for output
DateTimeFormatter outputFormat = new DateTimeFormatterBuilder()
.appendPattern("EEE MMM dd uuuu HH:mm:ss z")
.appendLiteral(" (")
.appendPattern("zzzz")
.appendLiteral(")")
.toFormatter();
// Get the string representation in the custom format
String strDate = zonedDateTime.format(outputFormat);
// Display the string representation in the custom format
System.out.println(strDate);
}
}
Output:
2020-08-27T00:00-04:00[America/New_York]
Thu Aug 27 2020 00:00:00 GMT-04:00 (Eastern Daylight Time)
Note: By any chance, if you also have difficulty to convert the timestamp into ZonedDateTime, you can refer other answers on this page and use this answer to solve the problem with formatting.
java.time
I recommend that you use java.time, the modern Java date and time API, exclusively for your date work. Instead of getting a Date or Timestamp from your database, since JDBC 4.2 (in the case of MySQL that’s many years now) get a modern LocalDate from your result set. An example:
PreparedStatement ps = yourDatabaseConnection.prepareStatement("select your_date from your_table;");
ResultSet rs = ps.executeQuery();
while (rs.next()) {
LocalDate date = rs.getObject("your_date", LocalDate.class);
// Do something with date
}
A LocalDate is a date without time of day and without time zone. So this will relieve you of all time zone trouble.
If you want to print the start of the day in North American Eastern time zone to the user in the format used in the question:
DateTimeFormatter etFormat = DateTimeFormatter.ofPattern("MM/dd/yyyy 'at' hh:mma v");
ZoneId zoneId = ZoneId.of("America/New_York");
LocalDate date = LocalDate.of(2020, Month.AUGUST, 27);
ZonedDateTime startOfDay = date.atStartOfDay(zoneId);
String result = startOfDay.format(etFormat);
System.out.println(result);
Output from this example is:
08/27/2020 at 12:00AM ET
Do use pattern letter v for time zone in the format pattern rather than hard-coding ET. The latter will produce false and confusing results when one day a junior programmer feeds a ZonedDateTime in an other time zone into the code.
What went wrong in your code?
It’s not clear to me how you got your date from your database. Apparently date even though declared a Date was really a Timestamp (a bad practice since the inheritance relationship between the two classes is really one of implementation, not a conceptual one) denoting the start of the day in UTC. toLocalDateTime() is a dangerous and often meaningless call: it uses the time zone of the JVM for converting the Timestamp to a LocalDateTime. At 0:00 UTC it is 8 PM the evening before in Eastern time zone, so your LocalDateTime becomes 2020-08-26T20:00. Next atZone(zoneId) only gives the correct time because zoneId happens to coincide with the JVM’s time zone used in the previous step.
Link
Oracle tutorial: Date Time explaining how to use java.time.
The date is converted with timezone set to GMT.
final static String datePattern = "EEE MM/dd/yyyy HH:mm:ss 'GMT'Z '('z')'";
DateFormat df = new SimpleDateFormat(datePattern, Locale.getDefault());
simpledateformat.setTimeZone(TimeZone.getTimeZone("GMT"))
simpleDateFormat.format(givenDate)
I have a date string in CST (24 Hours) and I want to convert it to GMT (12 Hours).
I have a java method like below which works fine when my system time is Kolkata time. (System where I run the java method)
But when my system is in Shanghai time, the GMT time comes incorrect.
String inputDate = "01-19-2017 06:01 CST";
SimpleDateFormat inputFormatter = new SimpleDateFormat("MM-dd-yyyy hh:mm Z");
parsedInput = inputFormatter.parse(inputDate);
// parsedInput -> Tue Jan 19 06:01:00 CST 2017 -> When system time is Shanghai time
// parsedInput -> Thu Jan 19 17:31:00 IST 2017 -> When system time is Kolkata time
SimpleDateFormat formatter = new SimpleDateFormat("MM-dd-yyyy hh:mm a Z");
TimeZone gmt = TimeZone.getTimeZone("GMT");
formatter.setTimeZone(gmt);
String formattedDate = formatter.format(parsedInput);
// formattedDate -> 01-18-2017 10:01 PM +0000 -> When system time is Shanghai time (Incorrect)
// formattedDate -> 01-19-2017 12:01 PM +0000 -> When system time is Kolkata time
Avoid pseudo time zones
The 3-4 letter time zone abbreviations such as CST are not actual time zones. They are not standardized. They are not even unique!
Your CST might be “China Standard Time” or might be “Central Standard Time” in the Americas, or might be something else. There is no way to know which one.
Another example: IST might mean “India Standard Time” or “Ireland Standard Time” or others.
Deciphering these pseudo-zones reliably is impossible. The Joda-Time library has a wise policy of refusing to even try. Unfortunately the java.time classes make a guess when parsing, but the result may not be the zone you expect.
So never use these useless pseudo-zones. Use a proper time zone name in the format of continent/region such as America/Chicago, Asia/Kolkata, Pacific/Auckland.
Avoid legacy date-time classes
You are using the troublesome old date-time classes that are now legacy, supplanted by the java.time classes.
Workaround
If you know all your inputs are intended for the same time zone, then lop off the pseudo-zone and process as a LocalDateTime, apply the intended zone as a ZoneId to produce a ZonedDateDate. From that you can extract an Instant for UTC time.
String input = "01-19-2017 06:01".replace( " " , "T" ) ; // Insert a “T” to comply with standard ISO 8601 format used by default in java.time.
LocalDateTime ldt = LocalDateTime.parse( input ); // Lacks any concept of time zone or offset-from-UTC. So *not* an actual moment on the timeline.
ZoneId z = ZoneId.of( "America/Chicago" ); // Assuming “CST” meant this zone in North America.
ZonedDateTime zdt = ldt.atZone( z ); // Assign a time zone to determine an actual moment on the timeline.
Instant instant = zdt.toInstant(); // Extract a value in UTC.
You may choose to see that same moment through the lens of the wall-clock time in India.
ZonedDateTime zdtKolkata = zdt.withZoneSameInstant( ZoneId.of( "Asia/Kolkata" ) ) ;
Never rely on default zone
Your JVM’s current default time zone can be changed at any moment by any code in any thread of any app executing within that JVM. Since this can change at any moment you cannot rely on a certain value.
When you omit the optional argument for time zone, the date-time classes implicitly silently apply the current default time zone. So the solution is simple: Always specify the expected/desired time zone.
Notice how the code example above specifies the zone at every opportunity.
(Ditto for Locale, by the way. Specify explicitly rather than rely on current default.)
Your problem is the ambiguity of CST. In most cases SimpleDateFormat understands CST as Central Standard Time as you had expected. But when your computer is running Shanghai Time, this becomes the time zone of the formatter’s calendar, and then it suddenly understands CST as China Standard Time, the same as Shanghai time.
Therefore Darshan Mehta’s solution, setting inputFormatter’s time zone to something other than China Standard Time, works on my computer. I don’t know why it didn’t work on yours (I set it to TimeZone.getTimeZone("America/Chicago") to match the intended interpretation of CST).
The correct and good solution, though, is to avoid the three and four letter time zone abbreviations completely. Yours is just one example out of many where they cause trouble. If you can, give your input string with an explicit zone offset from UTC, such is never ambiguous:
String inputDate = "01-19-2017 06:01 -0600";
Now your code works as expected no matter your computer’s time zone setting. The Z in the pattern string you already have matches -0600 nicely.
All of this said, if you can use the Java 8 date and time classes, you can do yourself a favour of switching over to them. I hesitate to call them “Java 8 date and time classes” because they have also been backported to Java 6 and 7, so if you can live with a library dependency until you get to Java 8, you should have every chance. The newer classes are significantly more programmer-friendly and convenient to work with. A simple example to get you started:
String inputDate = "01-19-2017 06:01 -0600";
DateTimeFormatter inputFormatter = DateTimeFormatter.ofPattern("MM-dd-yyyy HH:mm Z");
ZonedDateTime parsedInput = ZonedDateTime.parse(inputDate, inputFormatter);
OffsetDateTime gmtTime = parsedInput.toOffsetDateTime().withOffsetSameInstant(ZoneOffset.UTC);
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM-dd-yyyy hh:mm a Z");
String formattedDate = gmtTime.format(formatter);
System.out.println(formattedDate); // prints 01-19-2017 12:01 PM +0000
Try setting the TimeZone to inputFormatter as well, e.g.:
SimpleDateFormat inputFormatter = new SimpleDateFormat("MM-dd-yyyy hh:mm Z");
inputFormatter.setTimeZone(TimeZone.getTimeZone("GMT"));
If you don't specify the time zone, it takes the default value into account which is Asia/Shanghai in your case and hence, incorrect result.
You can reproduce it in your current system by replacing GMT with Asia/Shanghai in the above snippett
Given that my default TimeZone is Europe/Paris:
System.out.println("Current Timezone: " + TimeZone.getDefault());
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssX");
String dateStrIn = "2016-08-01T00:00:00Z";
Date date = dateFormat.parse(dateStrIn);
String dateStrOut = dateFormat.format(date);
System.out.println("Input date String: "+dateStrIn);
System.out.println("Date.toString() "+date);
System.out.println("Output date String: "+dateStrOut);
The output is:
Current Timezone: sun.util.calendar.ZoneInfo[id="Europe/Paris",offset=3600000,dstSavings=3600000,useDaylight=true,transitions=184,lastRule=java.util.SimpleTimeZone[id=Europe/Paris,offset=3600000,dstSavings=3600000,useDaylight=true,startYear=0,startMode=2,startMonth=2,startDay=-1,startDayOfWeek=1,startTime=3600000,startTimeMode=2,endMode=2,endMonth=9,endDay=-1,endDayOfWeek=1,endTime=3600000,endTimeMode=2]]
Input date String: 2016-08-01T00:00:00Z
Date.toString() Mon Aug 01 02:00:00 CEST 2016
Output date String: 2016-08-01T02:00:00+02
Now, I repeat the execution but setting a different default TimeZone (UTC):
TimeZone.setDefault(TimeZone.getTimeZone("UTC"));
System.out.println("Current Timezone: " + TimeZone.getDefault());
...
And this is the output:
Current Timezone: sun.util.calendar.ZoneInfo[id="UTC",offset=0,dstSavings=0,useDaylight=false,transitions=0,lastRule=null]
Input date String: 2016-08-01T00:00:00Z
Date.toString() Mon Aug 01 00:00:00 UTC 2016
Output date String: 2016-08-01T02:00:00+02
Date.toString() has correctly taken into account the TimeZone change. However, the String gotten from dateFormat.format(date); is still showing +02 instead of Z or +00, why?
Using standard Java API, is there any way to force the formatting according to a selected TimeZone?
UPDATE:
Jesper's solution works in almost all cases, but I have come across this one (using Canary Island's summer time zone WEST) in which it doesn't:
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss z");
dateFormat.setTimeZone(TimeZone.getTimeZone("Europe/Paris"));
TimeZone.setDefault(TimeZone.getTimeZone("Europe/Paris"));
System.out.println("Current Timezone: " + TimeZone.getDefault());
String dateStrIn = "2016-08-01T08:00:00 WEST";
Date date = dateFormat.parse(dateStrIn);
String dateStrOut = dateFormat.format(date);
System.out.println("Input date String: "+dateStrIn);
System.out.println("Date.toString() "+date);
System.out.println("Output date String: "+dateStrOut);
Output:
Current Timezone: sun.util.calendar.ZoneInfo[id="Europe/Paris",offset=3600000,dstSavings=3600000,useDaylight=true,transitions=184,lastRule=java.util.SimpleTimeZone[id=Europe/Paris,offset=3600000,dstSavings=3600000,useDaylight=true,startYear=0,startMode=2,startMonth=2,startDay=-1,startDayOfWeek=1,startTime=3600000,startTimeMode=2,endMode=2,endMonth=9,endDay=-1,endDayOfWeek=1,endTime=3600000,endTimeMode=2]]
Input date String: 2016-08-01T08:00:00 WEST
Date.toString() Mon Aug 01 09:00:00 CEST 2016
Output date String: 2016-08-01T08:00:00 WEST
You can see that Output date String is still expressed in WEST.
If, for instance, I change the initial dateStrIn to: String dateStrIn = "2016-08-01T08:00:00 GMT";, then the Output date String is expressed in CEST as espected:
Output date String: 2016-08-01T10:00:00 CEST
Could it be a bug?
UPDATE 2:
Another example
Default TimeZone for both Date and SimpleDateFormat: "Europe/Paris"
Input String: "2016-08-01T08:00:00 WET"
Output:
Date.toString() Mon Aug 01 10:00:00 CEST 2016
Output date String: 2016-08-01T09:00:00 WEST
Notice that dateFormat.format(date); has produced a WEST date string. From WET -> WEST when it should be WET -> CEST.
Instead of setting the default time zone, set the time zone on your SimpleDateFormat object:
dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
This will make the SimpleDateFormat object format your Date object in the UTC time zone.
If you're using Java 8, consider using the new date and time API in the package java.time instead of the old java.util.Date and java.text.SimpleDateFormat.
You torture yourself by using the troublesome old legacy date-time classes now outmoded by the java.time framework.
tl;dr
ZonedDateTime.ofInstant( Instant.parse( "2016-08-01T00:00:00Z" ) , ZoneId.of( "Europe/Paris" ) )
java.time
The java.time framework is built into Java 8 and later. These classes supplant the old troublesome date-time classes such as java.util.Date, .Calendar, & java.text.SimpleDateFormat. The Joda-Time team also advises migration to java.time.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations.
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport and further adapted to Android in ThreeTenABP.
Instant
The Z on the end of your input string 2016-08-01T00:00:00Z is short for Zulu and means UTC. Represented in java.time by the Instant class with a resolution up to nanoseconds.
Instant instant = Instant.parse ( "2016-08-01T00:00:00Z" );
ZonedDateTime
Specify a time zone via ZoneId to get a ZonedDateTime.
In the summer, Paris time is two hours ahead of UTC. So the same moment as seen on a clock on the wall in Paris is 2 AM rather than midnight, on same date of August 1st.
ZoneId zoneId_Paris = ZoneId.of ( "Europe/Paris" );
ZonedDateTime zdt_Paris = ZonedDateTime.ofInstant ( instant , zoneId_Paris );
You can adjust into another time zone such as Atlantic/Canary. For this date in the summer, the time is one hour ahead of UTC. Result is 1 AM rather than midnight.
ZoneId zoneId_Canary = ZoneId.of ( "Atlantic/Canary" );
ZonedDateTime zdt_Canary = zdt_Paris.withZoneSameInstant ( zoneId_Canary );
Dump to console.
System.out.println ( "instant: " + instant + " | zdt_Paris: " + zdt_Paris + " | zdt_Canary: " + zdt_Canary );
instant: 2016-08-01T00:00:00Z | zdt_Paris: 2016-08-01T02:00+02:00[Europe/Paris] | zdt_Canary: 2016-08-01T01:00+01:00[Atlantic/Canary]
All three of these objects (UTC, Paris, Canary) represent the very same simultaneous moment in history, the same single point on the timeline. Each is viewed through the lens of a different wall-clock time.
Real Time Zones
Avoid 3-4 letter zone abbreviations such as WET and WEST. These are not real time zones, not standardized, and not even unique(!).
Europe/Paris and Atlantic/Canary are proper time zone names, in the format of continent/region.
The answer to this mystery was on the Javadoc:
DateFormat.parse(String source, ParsePosition pos)
This parsing operation uses the calendar to produce a Date. As a
result, the calendar's date-time fields and the TimeZone value may
have been overwritten, depending on subclass implementations. Any
TimeZone value that has previously been set by a call to setTimeZone
may need to be restored for further operations.
Setting the TimeZone after parsing works it out:
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss z");
TimeZone.setDefault(TimeZone.getTimeZone("Europe/Paris"));
System.out.println("Current Timezone: " + TimeZone.getDefault());
String dateStrIn = "2016-08-01T08:00:00 WET";
Date date = dateFormat.parse(dateStrIn);
dateFormat.setTimeZone(TimeZone.getTimeZone("Europe/Paris"));
String dateStrOut = dateFormat.format(date);
System.out.println("Input date String: "+dateStrIn);
System.out.println("Date.toString() "+date);
System.out.println("Output date String: "+dateStrOut);
Right output:
Current Timezone: sun.util.calendar.ZoneInfo[id="Europe/Paris",offset=3600000,dstSavings=3600000,useDaylight=true,transitions=184,lastRule=java.util.SimpleTimeZone[id=Europe/Paris,offset=3600000,dstSavings=3600000,useDaylight=true,startYear=0,startMode=2,startMonth=2,startDay=-1,startDayOfWeek=1,startTime=3600000,startTimeMode=2,endMode=2,endMonth=9,endDay=-1,endDayOfWeek=1,endTime=3600000,endTimeMode=2]]
Input date String: 2016-08-01T08:00:00 WET
Date.toString() Mon Aug 01 10:00:00 CEST 2016
Output date String: 2016-08-01T10:00:00 CEST
No, its not a bug.
You have to first understand how Date class works. It is nothing but a wrapper over the number of milliseconds since the epoch, expressed in long. Hence, whichever timezone it may be, the underlying value of the date object remains the same. You can never really change the timezone of a Date class. You can only represent a String format of a date instance using a SimpleDateFormat class. This representation might have different time zones, based on which you are using while creating the SimpleDateFormatobject.
Again, you need to check the toString method of the Date class. It always prints the date with the default time zone.
Edit
You should look at the SimpleDateFormat.parse() definition as well. The JDK says that,
The TimeZone value may be overwritten, depending on the given pattern and the time zone value in text. Any TimeZone value that has previously been set by a call to setTimeZone may need to be restored for further operations.
I've been trying to convert the time since epoch until today and display it in Eastern Standard Time. Here is what outputs on the remote machine (it's remotely hosted):
Date now = new Date(System.currentTimeMillis());
System.out.println(now.toString());
// Thu Apr 24 14:36:11 MST 2014
No idea what MST is, but I want to get the current milliseconds since epoch in EST, and display the result in EST.
No matter what I do, I can't get daylights savings to work (it's currently Daylights Savings Time in the EST Time Zone); I either end up in PST, GMT or UTC, and when I do get "EST" it's either some random value or 1 hour behind or 3 hours behind.
I would like the output to be formatted using this DateFormat:
DateFormat EXPIRE_FORMAT = new SimpleDateFormat("MMM dd, yyyy h:mm a z");
Just set the time zone you want the time to be displayed in using DateFormat#setTimeZone(TimeZone)
Date now = new Date(System.currentTimeMillis());
DateFormat EXPIRE_FORMAT = new SimpleDateFormat("MMM dd, yyyy h:mm a z");
EXPIRE_FORMAT.setTimeZone(TimeZone.getTimeZone("America/Montreal")); // or whatever relevant TimeZone id
System.out.println(EXPIRE_FORMAT.format(now));
AFAIK, there is no EST currently. It's all EDT in Spring.
The above prints
Apr 24, 2014 5:53 PM EDT
The comments and the answer by Sotirios Delimanolis are correct.
Avoid 3 or 4 Letter Time Zone Codes
You should avoid the 3 or 4 letter codes for time zones as they are neither standardized nor unique. Instead use proper time zone names, usually a continent+city.
Avoid j.u.Date
The java.util.Date and .Calendar & SimpleDateFormat classes bundled with Java are notoriously troublesome. Use a decent date-time library with an updated time zone database. For Java, that means either Joda-Time or the new java.time package in Java 8 (inspired by Joda-Time).
Avoid Milliseconds-Since-Epoch
I suggest you avoid working with milliseconds since epoch. Gets confusing fast as the number is meaningless when read by a human. Let the date-time library manage the milliseconds for you.
Specify Time Zone
Generally best to specify the desired/intended time zone. If you omit the time zone, all the major date-time libraries (java.util.Date, Joda-Time, java.time) apply the JVM's default time zone.
Joda-Time Example
Example code in Joda-Time 2.3.
DateTimeZone timeZoneToronto = DateTimeZone.forID( "America/Toronto" );
DateTime dateTimeToronto = new DateTime( timeZoneToronto ); // Current moment.
DateTime dateTimeUTC = dateTimeToronto.withZone( DateTimeZone.UTC );
DateTime dateTimeParis = dateTimeToronto.withZone( DateTimeZone.forID( "Europe/Paris" ) );
If you really want the milliseconds since epoch, call the getMillis method. In example code above, all three DateTime objects have the same number of milliseconds-since-epoch.
long millis = dateTimeToronto.getMillis();
If you need a java.util.Date for use with other classes…
java.util.Date date = dateTimeToronto.toDate();
While Joda-Time uses the ISO 8601 standard formats as its defaults, you may specify other formats for generating strings.
DateTimeFormatter formatter = DateTimeFormat.forPattern( "MMM dd, yyyy h:mm a z" );
String output = formatter.print( dateTimeToronto );
I have a Calendar object [ localDate ] which is in EST : say Nov 6, 15:34... and i set the timeZone to GMT+5:30...
Now when i do the Calendar.HOUR_OF_DAY it returns me 2... which i know is perfect.. since its 15:34 + 5 hrs to GMT and then +5:30 to the timezone.. which just means.. 26:04 which is 2 of 7th .
However , the date still stays as Nov 6... and localDate.getTime() still returns Nov 6.. and even when i print the localDate.. it shows the timezone as +5:30 , but the day and everything else is still as the original local Time..[ i.e Nov 6 ]
I am simply unable to understand why so...
Edit ::
So i understand that i do not need to change the date along with the timezone.. Only change the way date is displayed suited to that location and that can be done using the timezone that has been set.
localDate.getTime() returns a java.util.Date which is a quantity of raw time since a fixed point. Timezones only affect the human readable representation of the point in time.
15:34 Nov 6th UTC - 5
and
02:04 Nov 7th UTC + 5:30
are both the exact same point in absolute time. It's just two different human ways of describing the same instant.
So changing the timezone on the calendar has no effect on the value returned by getTime()
Date objects do not have a timezone - a Date object represents an "absolute" moment in time. When you print a Date object (by implicitly or explicitly calling toString() on it):
Date date = ...;
System.out.println(date);
then it will be formatted using some default format that will show the date in your local timezone - no matter if you got the Date object from a Calendar which was set to a different timezone.
If you want to display the Date in a different timezone, use a DateFormat object and set the timezone that you want to display your date in on that object:
Date date = ...;
DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss Z");
df.setTimeZone(TimeZone.getTimeZone("UTC")); // For example, UTC
// Prints 'date' in UTC
System.out.println(df.format(date));
Question Is Not Clear
Your question is confusing.
You may be confused about the meaning of time zones. As the correct answers by Jesper and Affe said, shifting time zones does not change the point on the time line of the Universe. Suppose Bob in New York US calls Susan in Reykjavík Iceland. Iceland uses UTC as their time zone all year round. Bob and Susan are speaking to each other at the same moment in time. But if Bob looks at the clock on his wall, he sees a time displayed that is 5 hours earlier than a clock on Susan’s wall. New York has a five hour offset behind UTC (-5:00).
Another problem with your question: You also talk about a 5:00 time zone offset as well as a 5:30 offset. Which is it? Or do you have two time zones in mind as well as GMT/UTC?
Joda-Time
I'll take a stab at giving you a bit of example source code.
The Joda-Time library makes date-time work easier.
// © 2013 Basil Bourque. This source code may be used freely forever by anyone taking full responsibility for doing so.
// Use time zone names rather than explicit number of hours offset is generally a good thing.
// Affords Joda-Time an opportunity to make adjustments such as Daylight Saving Time (DST).
// Question asked:
// (1) Start with a US east coast time (Standard offset of -5:00) of November 6, 2013 15:34.
// (2) Move that datetime to UTC (GMT) time zone (no offset).
// (3) Move that datetime to Kolkata (formerly known as Calcutta) India time zone (Standard offset of +05:30).
// Joda-Time has deprecated use of 3-letter time zone codes because of their inconsistency. Use other identifier for zone.
// Time Zone list: http://joda-time.sourceforge.net/timezones.html (Possibly out-dated, read note on that page)
org.joda.time.DateTimeZone newyorkTimeZone = org.joda.time.DateTimeZone.forID( "America/New_York" );
org.joda.time.DateTimeZone kolkataTimeZone = org.joda.time.DateTimeZone.forID( "Asia/Kolkata" );
// Question calls for: EST Nov 6, 15:34 (Standard offset of -5:00).
// This DateTime constructor calls for passing: year, month, day, time zone.
org.joda.time.DateTime dateTimeInNewYork = new org.joda.time.DateTime( 2013, org.joda.time.DateTimeConstants.NOVEMBER, 6, 15, 34, newyorkTimeZone );
// Move to UTC time zone (no offset).
org.joda.time.DateTime dateTimeUtc = dateTimeInNewYork.toDateTime( org.joda.time.DateTimeZone.UTC );
// Move to Kolkata IN time zone (Standard offlet of +05:30).
org.joda.time.DateTime dateTimeInKolkata = dateTimeUtc.toDateTime( kolkataTimeZone ); // Or invoke this method on dateTimeInNewYork, does not matter which.
// All three of these date-time objects represent the same moment in the time-line of the Universe,
// but present themselves with different time-zone offsets.
System.out.println( "dateTimeInNewYork: " + dateTimeInNewYork );
System.out.println( "dateTimeUtc: " + dateTimeUtc );
System.out.println( "dateTimeInKolkata: " + dateTimeInKolkata );
When run…
dateTimeInNewYork: 2013-11-06T15:34:00.000-05:00
dateTimeUtc: 2013-11-06T20:34:00.000Z
dateTimeInKolkata: 2013-11-07T02:04:00.000+05:30
About Joda-Time…
// Joda-Time - The popular alternative to Sun/Oracle's notoriously bad date, time, and calendar classes bundled with Java 7 and earlier.
// http://www.joda.org/joda-time/
// Joda-Time will become outmoded by the JSR 310 Date and Time API introduced in Java 8.
// JSR 310 was inspired by Joda-Time but is not directly based on it.
// http://jcp.org/en/jsr/detail?id=310
// By default, Joda-Time produces strings in the standard ISO 8601 format.
// https://en.wikipedia.org/wiki/ISO_8601
// About Daylight Saving Time (DST): https://en.wikipedia.org/wiki/Daylight_saving_time
// Time Zone list: http://joda-time.sourceforge.net/timezones.html