Converting to UTC considering daylight saving - java

I have a date, for example Thu April 17 09:03:01 GMT 2014 in the timezone:
sun.util.calendar.ZoneInfo[id="Europe/London",offset=0,dstSavings=3600000,useDaylight=true,transitions=242,lastRule=java.util.SimpleTimeZone[id=Europe/London,offset=0,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]]
and everytime a try to convert to UTC it returns Thu April 17 10:03:01 GMT 2014
This does not make sense because the corresponding UTC time is actually Thu April 17 08:03:01 GMT 2014 since that the in my timezone time is added 1hour due to daylight savings.
The code I use to convert is this:
//timeZone - id="Europe/London"
public static Date timeZoneConvertDate(Date date, TimeZone timeZone) {
SimpleDateFormat sdf = new SimpleDateFormat();
sdf.setTimeZone(timeZone);
sdf.applyPattern("dd-MM-yyyy HH:mm:ss");
String newDate = sdf.format(date);
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
try {
Date nd = sdf.parse(newDate);
return nd;
} catch (ParseException e) {
return null;
}
}
Could someone explain what I'm doing wrong?

tl;dr
A Date has no timezone associated with it, so you cannot create a method that adjusts the timezone of a date object. You need to work with Calendar objects if you want to retain TZ information or, preferably, take a look at Joda-Time.
Explanation of Your Output
A Date value has no timezone information; it's merely the number of milliseconds since the epoch. With that in mind, let's see what you're doing:
SimpleDateFormat sdf = new SimpleDateFormat();
sdf.setTimeZone(timeZone);
sdf.applyPattern("dd-MM-yyyy HH:mm:ss");
String newDate = sdf.format(date);
This part of your code creates a formatter that will print the date in the London timezone. So the result you'll get at the time of writing is approximately: 17-04-2014 11:38:15 (assuming you just created your date object).
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
try {
Date nd = sdf.parse(newDate);
return nd;
} catch (ParseException e) {
return null;
}
Here you tell the date parser to read the date as though it were a UTC date. It uses that information to know how many milliseconds since the epoch have passed. The date object you get back still has no timezone associated with it.
UTC is an hour behind British Summer Time, so it will create a date object that appears an hour ahead when printed in the BST timezone. So when I print nd, I get: Thu Apr 17 12:38:15 BST 2014.

No Time Zone In java.util.Date
As the correct answer by Duncan said a java.util.Date has no time zone component. Confusingly its toString method applies the JVM's default time zone. To display in another time zone, use SimpleDateFormat to apply an adjustment.
Even better, avoid the notoriously troublesome java.util.Date, .Calendar, and SimpleDateFormat. Use either Joda-Time or the new java.time package in Java 8.
Joda-Time
In Joda-Time, a DateTime object truly does contain an assigned time zone. If you do not specify a time zone, the JVM's default time zone is assigned.
DateTimeZone timeZone = DateTimeZone.forID( "Europe/London" );
DateTime dateTime = new DateTime( 2014, 4, 17, 9, 3, 1, timeZone );
DateTime dateTimeUtc = dateTime.withZone( DateTimeZone.UTC );
DateTime dateTimeIndia = dateTime.withZone( DateTimeZone.forID( "Asia/Kolkata" ) );
When run…
dateTime: 2014-04-17T09:03:01.000+01:00
dateTimeUtc: 2014-04-17T08:03:01.000Z
dateTimeIndia: 2014-04-17T13:33:01.000+05:30 (note the half-hour difference, +05:30)
You can easily convert back and forth to java.util.Date.
DateTime dateTime = new DateTime( myJUDate, timeZone );
…and…
Java.util.Date date = dateTime.toDate();

Related

Wrong value while converting UTC date to a given timezone

I am trying to convert a UTC date String of the format 2020-06-09T06:30:00Z to a Timezone like Asia/Calcutta.
The time offset between UTC and Asia/Calcutta is +5:30, so the expected result on converting 2020-06-09T06:30:00Z to Asia/Calcutta is 2020-06-09T12:00:00Z but I am getting 2020-06-09T01:00:00Z
String utcDate = "2020-06-09T06:30:00Z";
String timezone = "Asia/Calcutta";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss'Z'");
LocalDateTime date = LocalDateTime.parse(utcDate, formatter); //2020-06-09T06:30
ZonedDateTime zonedDate = ZonedDateTime.of(date, ZoneId.of(timezone)); //2020-06-09T06:30+05:30[Asia/Calcutta]
Date dateConverted = Date.from( zonedDate.toInstant()); //Tue Jun 09 01:00:00 UTC 2020
I think zonedDate.toInstant() is converting subtracting 5:30 instead of adding 5:30 to 2020-06-09T06:30. My machine is in UTC timezone. may be its converting to local time don't know what is the issue. Also tried below method, still same issue.
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
sdf.setTimeZone(TimeZone.getTimeZone(timezone));
sdf.parse(dateString);
java.time
I agree with you, you should strongly prefer to use java.time, the modern Java date and time API. It’s not complicated when you know how.
String utcDate = "2020-06-09T06:30:00Z";
String timezone = "Asia/Calcutta";
ZoneId zone = ZoneId.of(timezone);
ZonedDateTime zdt = Instant.parse(utcDate).atZone(zone);
System.out.println("zdt: " + zdt);
Output is:
zdt: 2020-06-09T12:00+05:30[Asia/Calcutta]
You notice that the time of day in the ZonedDateTime is 12:00 as you had expected. The trailing Z that you also said you expected is wrong, though. Z means an offset of 0 from UTC, so since the offset is +05:30, we are very happy not to have the Z there.
If what you needed was an old-fashioned Date object, presumably for a legacy API that you don’t want to upgrade just now, there’s no reason to convert to your time zone first. This works:
Date oldfashionedDate = Date.from(Instant.parse(utcDate));
System.out.println("oldfashionedDate: " + oldfashionedDate);
Output in my time zone is:
oldfashionedDate: Tue Jun 09 08:30:00 CEST 2020
You may be in doubt whether the Date is right. It is. Since I am in Europe/Copenhagen time zone, currently at offset +02:00, the Date prints in this time zone, so the time of day is 8:30 (the Date doesn’t hold a time zone or offset). If instead I run in Asia/Calcutta time zone:
oldfashionedDate: Tue Jun 09 12:00:00 IST 2020
You notice IST for India Standard Time instead of CEST for Central European Summer Time. And the time is 12:00 as expected.
Points for you to take with you
Never hardcode Z as a literal in a format pattern string. As I said, it’s an offset, so it needs to be parsed as an offset.
For the same reason don’t parse into a LocalDateTime. A LocalDateTime. hasn’t got any offset, so you are losing information.
In this case use no formatter at all. Your format is ISO 8601, and Instant parses it as its default, that is, without any explicit formatter (OffsetDateTime and ZonedDateTime do too).
Make the conversion from UTC to Asia/Calcutta. It seems to me that you were doing the opposite conversion.
Link
Wikipedia article: ISO 8601
Got it work using SimpleDateFormat as shown below. But anyone coming across this issue should probably use ZonedDateTime.
String utcDate = "2020-06-09T06:30:00Z";
String timezone = "Asia/Calcutta";
SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
sdf1.setTimeZone(TimeZone.getTimeZone("UTC"));
Date date = sdf1.parse(utcDate); // Tue Jun 09 06:30:00 UTC 2020
SimpleDateFormat sdf2 = new SimpleDateFormat("dd-M-yyyy hh:mm:ss a");
sdf2.setTimeZone(TimeZone.getTimeZone(timezone));
String sDateInZone = sdf2.format(date); // 09-6-2020 12:00:00 PM
SimpleDateFormat formatter = new SimpleDateFormat("dd-M-yyyy hh:mm:ss a");
Date dateInZone = formatter.parse(sDateInZone); // Tue Jun 09 12:00:00 UTC 2020
EDIT: Got it to work using ZonedDateTime also as shown below:
String utcDate = "2020-06-09T06:30:00Z";
String timezone = "Asia/Calcutta";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss'Z'");
LocalDateTime dateUtc = LocalDateTime.parse(utcDate, formatter);
ZonedDateTime utcZonedDateTime = dateUtc.atZone(ZoneId.systemDefault());
ZoneId zoneId = ZoneId.of(timezone);
ZonedDateTime zonedDateTime = utcZonedDateTime.withZoneSameInstant(zoneId);
String zoneDateString = formatter.format(zonedDateTime);
Date date = Date.from(LocalDateTime.parse(zoneDateString, formatter).atZone(ZoneId.systemDefault()).toInstant());

my joda time zone messup

guys.
im newbie in using joda time api. so here is my question. Ive app server deploy somewhere in the western region and the date fixed to the particular time , Fri Feb 6 08:50:54 UTC 2015.
however, i try to use joda time zone to change the timezone to my country. it didnt worked out. i have run out of ideas. below is my code :
java.util.Date dateIn = new java.util.Date();
DateTime dateTimeUtc = new DateTime( dateIn, DateTimeZone.UTC );
System.out.println("date time utc : " + dateTimeUtc);
DateTimeZone timeZoneLos_Angeles = DateTimeZone.forID( "America/Los_Angeles" ); // Adjust time zone to United States.
DateTime dateTimeLos_Angeles = dateTimeUtc.withZone( timeZoneLos_Angeles );
System.out.println("los angeles date time : " + dateTimeLos_Angeles.toDate());
DateTimeZone timeZoneMalaysia = DateTimeZone.forID( "Asia/Singapore" );
DateTime dateTimeKL = dateTimeLos_Angeles.withZone( timeZoneMalaysia );
System.out.println("KL date time : " + dateTimeKL.toDate());
java.util.Date newDate = dateTimeKL.toDate();
System.out.println("after convert to j.u.Date : " + newDate);
the output:
date time utc : 2015-02-06T08:58:29.127Z
los angeles date time : Fri Feb 06 16:58:29 SGT 2015
KL date time : Fri Feb 06 16:58:29 SGT 2015
after convert to j.u.Date : Fri Feb 06 16:58:29 SGT 2015
i dont know what's going on now. joda time is using my local machine time.
can u guys explain what is happening here? am i accessing joda time in wrong way. or is it my mistake?
A java.util.Date is basically the same thing as a joda-time Instant: an instant on the universal time scale. It doesn't have any time zone. It's just a number of milliseconds wrapped into an object. So when you call toString() on a java.util.Date instance, this object tries to make this number of millisecond readable to you, and transforms it to a readable date using the default timezone of the JVM: SGT in this case.
If you want to see a date in a given timezone, then print the DateTime instance itself (which contains an instant and a time zone) instead of transforming it to a Date (which loses the timezone information), or use a SimpleDateFormat configured with the timezone you want to display the java.util.Date to a string in the wanted time zone.
Joda Time provides a quality replacement for the Java date and time classes. The design allows for multiple calendar systems, while still providing a simple API. Converting a Joda DateTime object from one timezone to another is pretty easy and saves you quite a number of lines of code. See method below.
public static Date convertJodaTimezone(LocalDateTime date, String srcTz, String destTz) {
DateTime srcDateTime = date.toDateTime(DateTimeZone.forID(srcTz));
DateTime dstDateTime = srcDateTime.withZone(DateTimeZone.forID(destTz));
return dstDateTime.toLocalDateTime().toDateTime().toDate();
}
Since Joda Time has its own class for storing Date and Calendar objects, the DateTime class has its own toDate() method for converting it to a java.util.Date.
For further example check this link
I reused your code and did some changes. The commented lines were the previous implementation so that you can compare the difference with the new implementation.
Date dateIn = new Date();
DateTime dateTimeUtc = new DateTime( dateIn, DateTimeZone.UTC );
System.out.println("date time utc : " + dateTimeUtc);
DateTimeZone timeZoneLos_Angeles = DateTimeZone.forID( "America/Los_Angeles" ); // Adjust time zone to United States.
//DateTime dateTimeLos_Angeles = dateTimeUtc.withZone( timeZoneLos_Angeles );
DateTime dateTimeLos_Angeles = dateTimeUtc.withZone(timeZoneLos_Angeles);
//System.out.println("los angeles date time : " + dateTimeLos_Angeles.toDate());
System.out.println("los angeles date time : " + dateTimeLos_Angeles.toLocalDateTime().toDate());
DateTimeZone timeZoneMalaysia = DateTimeZone.forID( "Asia/Singapore" );
DateTime dateTimeKL = dateTimeUtc.withZone(timeZoneMalaysia);
//System.out.println("KL date time : " + dateTimeKL.toDate());
System.out.println("KL date time : " + dateTimeKL.toLocalDateTime().toDate());
//Date newDate = dateTimeKL.toDate();
Date newDate = dateTimeKL.toLocalDateTime().toDate();
System.out.println("after convert to j.u.Date : " + newDate);
I hope this one works for you. If you can optimize this code further then great. Cheers!

Get only TimeZone field from new Date() in java

Requirement : I want to get only TimeZone field from new Date(), As of now from new Date() ,I am getting result as
Wed Jul 23 19:37:20 GMT+05:30 2014,But I want only GMT+05:30,Is there any way to get only this?
PS:I dont want to use split for getting timezone field.because this is my final option for achieving above requirement.
You should use the Calendar class and likely, the implementation GregorianCalendar. A lot of the Date functions have been deprecated in favor of using Calendar. Java 8 has the Clock API, but I'll assume Java 7 here.
That way you can do this:
Calendar calendar = new GregorianCalendar();
TimeZone tz = calendar.getTimeZone();
And work from there.
Assuming you have to work with a String input you can do something like this:
// format : dow mon dd hh:mm:ss zzz yyyy
String date = "Wed Jul 23 19:37:20 GMT+05:30 2014";
Pattern pattern = Pattern
.compile("^\\w{3}\\s\\w{3}\\s\\d{2}\\s\\d{2}:\\d{2}:\\d{2}\\s?(.*)\\s\\d{4}$");
Matcher matcher = pattern.matcher(date);
if (matcher.matches()) {
String timezone = matcher.group(1);
// beware : according to the Date.toString() documentation the timezone
// value can be empty
System.out.println(timezone);
} else {
System.out.println("doesn't match!");
}
import java.util package and use GregorianCalendar method.
int second, minute, hour;
GregorianCalendar date = new GregorianCalendar();
second = date.get(Calendar.SECOND);
minute = date.get(Calendar.MINUTE);
hour = date.get(Calendar.HOUR);
System.out.println("Current time is "+hour+" : "+minute+" : "+second);
Don't use Date and Time class of java.util package as their methods are deprecated means they may not be supported in future versions of JDK.
Generate String With Offset But No Date and No Time
Your question is inaccurate. A java.util.Date has no time zone (assumes to always be in UTC). The JVM's time zone is applied in the object' toString method and in other formatting code that generates a String representation. Therein lies your solution: use a date-time formatter that generates a String containing only the offset from UTC without the date or the time-of-day portions.
Avoid java.util.Date & .Calendar
Avoid using the bundled java.util.Date and .Calendar classes as they are notoriously troublesome. Instead use either Joda-Time or the new java.time package. Both support time zones as part of a date-time object.
Joda-Time
Here is how to generate a String representation of a DateTime in Joda-Time 2.3.
DateTime dateTime = new DateTime( DateTimeZone.forID( "Asia/Kolkata" ) );
DateTimeFormatter formatter = DateTimeFormat.forPattern( "ZZ" );
String offset = formatter.print( dateTime ); // generates: +05:30
In Joda-Time 2.3 you can ask a DateTime object for its assigned time zone as an object. You may then interrogate the DateTimeZone object.
DateTime dateTime = new DateTime( DateTimeZone.forID( "Asia/Kolkata" ) );
DateTimeZone timeZone = dateTime.getZone();
String id = timeZone.getID();

Convert IST to US timezones considering the daylight saving time in java

I have a date-time in IST. I want to convert it to US timezones based on input considering the daylight saving time,
if there is daylight saving time for the given date-time in java.
This is what i tried
function convert(Date dt,int toTimeZoneId){
Calendar cal = Calendar.getInstance();
cal.setTime(dt); // Geting time in IST
//Converted to GMT and set in cal
switch(toTimeZoneId){
case 1: tzTarget = TimeZone.getTimeZone("America/Adak");
offset = -10;
break;
case 2: tzTarget = TimeZone.getTimeZone("America/Anchorage");
offset = -9;
break;
case 3: tzTarget = TimeZone.getTimeZone("America/Los_Angeles");
offset = -8;
break;
case 4: tzTarget = TimeZone.getTimeZone("America/Denver");
offset = -7;
break;
case 5: tzTarget = TimeZone.getTimeZone("America/Chicago");
offset = -6;
break;
case 6: tzTarget = TimeZone.getTimeZone("America/New_York");
offset = -5;
break;
}
//converting from GMT to US timezones based on offset and dst
cal.setTimeZone(tzTarget);
dst = tzTarget.getDSTSavings();
dst = dst/3600000;
offset = offset + dst;
cal.add(Calendar.HOUR, offset);
Date date = cal.getTime();
System.out.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(date));
}
To just convert a given date to different time zones, you need to create the date formatter with appropriate time zone. A date instance is just a long value relative to epoch; it doesn't have time zone information. So we aren't converting it to a different time zone, we are just representing it in different time zones. That is why we need time zone information when we want to create a string representation of the date instance.
Here's some code to illustrate the above. I've just added the time zone to your date format string to make things clear.
/*
* Converts a specified time to different time zones
*/
public void convert(Date dt) {
// This prints: Date with default formatter: 2013-03-14 22:00:12 PDT
// As my machine is in PDT time zone
System.out.println("Date with default formatter: " + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss z").format(dt));
// This prints: Date with IST time zone formatter: 2013-03-15 10:30:12 GMT+05:30
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss z");
TimeZone tz = TimeZone.getTimeZone("GMT+0530");
sdf.setTimeZone(tz);
String dateIST = sdf.format(dt);
System.out.println("Date with IST time zone formatter: " + dateIST);
// This prints: Date CST time zone formatter: 2013-03-15 00:00:12 CDT
tz = TimeZone.getTimeZone("CST");
sdf.setTimeZone(tz);
System.out.println("Date CST time zone formatter: " + sdf.format(dt));
}
I think this is what you are trying to do - convert a given time to different time zones. To do that I don't think you need to add/subtract any offset, as you just want the same time represented in a different time zone and the TimeZone instance should be able to take care of that during formatting.
As for daylight saving, the TimeZone should be able to take care of that as well. If you notice in my example code, I've used CST to create TimeZone instance and CST is "GMT -06 hours". But the output it gives is in CDT, which is "GMT -05 hours", because this time zone instance uses daylight saving. So by using the appropriate time zone you should be able to handle daylight saving as well.
java.util.GregorianCalendar allows you create dates with timezones. Unfortunately, addition and subtraction suck from there. (How do you subtract Dates in Java?)
Since you're converting between two timezones, you can also make use of java.util.TimeZone and use the difference of tz1.getOffset(date) - tz2.getOffset(date). Mind the ordering when doing subtraction.
Joda-Time
Using Joda-Time makes this much easier. Or try the new java.time package in Java 8.
Here is some example code using Joda-Time 2.3. Search StackOverflow for many more examples.
India time…
DateTimeZone timeZone_India = DateTimeZone.forID( "Asia/Kolkata" );
DateTime dateTimeIndia = new DateTime( date, timeZone_India );
Adjusting the same moment for display as New York time…
DateTimeZone timeZone_NewYork = DateTimeZone.forID( "America/New_York" );
DateTime dateTimeNewYork = dateTimeIndia.withZone( timeZone_NewYork ); // Same moment, different wall-clock time.
Still the same moment, but in UTC (no time zone offset).
DateTime dateTimeUtc = dateTimeIndia.withZone( DateTimeZone.UTC );
Use Proper Time Zone Names
Avoid using 3-4 letter time zone codes. They are neither standardized nor unique. Your IST for example can mean either Irish Standard Time or India Standard Time. Use proper time zone names.

Parsing formatted Date String in another TimeZone to date object not working

I am trying to convert a formatted date String to Date object. Date String is formatted to some other timezone.
When I do sdf.parse(String) it returns me my System date object.
Code is as below,
static Date convertGMTTime(String timeZone, long longDate){
Date convertedTime = null;
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try{
Date date = new Date(longDate);
System.out.println("timezone: "+timeZone +", timestamp: "+date);
Locale locale = Locale.ENGLISH;
TimeZone destTimeZone = TimeZone.getTimeZone(timeZone);// TimeZone.getDefault();
System.out.println("Source timezone: "+destTimeZone);
/* DateFormat formatter = DateFormat.getDateTimeInstance(
DateFormat.DEFAULT,
DateFormat.DEFAULT,
locale);
formatter.setTimeZone(destTimeZone);*/
sdf.setTimeZone(destTimeZone);
String convertedDateStr = sdf.format(date);
System.out.println("convertedDateStr: "+convertedDateStr);
convertedTime = sdf.parse(convertedDateStr);
System.out.println("convertedTime: "+convertedTime + "sdf: "+sdf.getTimeZone());
}catch(Exception e){
e.printStackTrace();
}
return convertedTime;
}
I would appreciate if anyone could help and point out where I am going wrong.
Thanks in advance.
Output:
timezone: Atlantic/Cape_Verde, timestamp: Tue Jun 26 17:38:11 IST 2012
Source timezone: sun.util.calendar.ZoneInfo[id="Atlantic/Cape_Verde",offset=-3600000,dstSavings=0,useDaylight=false,transitions=6,lastRule=null]
convertedDateStr: 2012-06-26 11:08:11
convertedTime: Tue Jun 26 17:38:11 IST 2012
sdf:sun.util.calendar.ZoneInfo[id="Atlantic/Cape_Verde",offset=-3600000,dstSavings=0,useDaylight=false,transitions=6,lastRule=null]
Some more details to share, When I use another sdf object(without setting timezone for it), It do return me correct time and date but still timezone is picked from System clock
Code
static Date convertGMTTime(String timeZone, long longDate){
Date convertedTime = null;
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
SimpleDateFormat sdfParse = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try{
Date date = new Date(longDate);
TimeZone destTimeZone = TimeZone.getTimeZone(timeZone);// TimeZone.getDefault();
System.out.println("Source timezone: "+destTimeZone);
sdf.setTimeZone(destTimeZone);
String convertedDateStr = sdf.format(date);
System.out.println("convertedDateStr: "+convertedDateStr );
convertedTime = sdfParse.parse(convertedDateStr,new ParsePosition(0));
System.out.println("convertedTime: "+convertedTime + "sdf: "+sdf.getTimeZone());
}catch(Exception e){
e.printStackTrace();
}
return convertedTime;
}
Output
Source timezone: sun.util.calendar.ZoneInfo[id="Atlantic/Cape_Verde",offset=-3600000,dstSavings=0,useDaylight=false,transitions=6,lastRule=null]
convertedDateStr: 2012-06-26 12:24:56
convertedTime: Tue Jun 26 12:24:56 IST 2012
sdf: sun.util.calendar.ZoneInfo[id="Atlantic/Cape_Verde",offset=-3600000,dstSavings=0,useDaylight=false,transitions=6,lastRule=null]
I understand that when I do not assign timezone to sdf it takes System time zone, but why doesn't it show time in System time zone? I shows it in timezone as it was in String but Timezone is different.
Ans when I set timezone it returns date object as per my system time irrespective of the fact that sdf has some other time zone set.
Can anyone please explain the functional behavior for sdf.parse and sdf.format.
For me sdf.setTimeZone() does have its impact when we use format and it is nullified when we use sdf.parse(). I find it quite strange.
Appreciate help in this regard.
You already have a Date (or the number of milliseconds of the Date), so there is nothing to convert. A Date doesn't have any time zone. It's a universal instant in time. The time zone is relevant only when you display this date, because the date 65647678000 could be 12:38 in some time zone, but 10:38 in some other time zone. It's also relevant when you parse the String representation of a Date, because 10:38 is 65647678000 in some time zone, but is 65657678000 in some other.
While you don't display a Date object, or parse a String to a Date, you don't need to care about time zones. And to choose the time zone used when displaying/parsing it, set the time zone of the DateFormat, and then use DateFormat.format()/DateFormat.parse() to format/parse the date.
When you use Date.toString() to display a date, it will always use your current time zone.
I find it easier to understand what I mean by not thinking of a Date as a day, a month, a year, an hour, etc., but as a moment: "when Kennedy was shot". "When Kennedy was shot" is the same moment for everyone. But if you represent the moment "when Kennedy was shot" in Dallas time zone, it's not the same result as the result you get when you represent this same moment in Paris time zone.

Categories

Resources