Reputation: 9480
I am working on a project where I have to manipulate the dates. Here is the code snipper I have My time zone is IST and the conversion time zone is CST.
public class Sample {
public static Long time = 1418187600l;
public static TimeZone tz1 = TimeZone.getTimeZone("US/Central");
public static void main(String[] args) {
Calendar c1 = Calendar.getInstance();
System.out.println(c1.getTime()); // output1
c1.setTimeInMillis(time*1000);
System.out.println(c1.getTime());//output 2
System.out.println(c1.get(Calendar.DATE));
c1.setTimeZone(tz1);;
System.out.println(c1.getTime()); //output 3
System.out.println(c1.get(Calendar.DATE));
}
}
When I ran the program, I got
Wed Dec 10 13:03:42 IST 2014
for line which was correct.
Then set the time to 1418187600, this output was also correct.
Wed Dec 10 10:30:00 IST 2014
However when the set the timezone to CST, and tried outputting the date, it returned the same
Wed Dec 10 10:30:00 IST 2014
while it should have returned Dec 09 2014 23:00:00.
However when I tried Calendar.data, it showed the correct date. can anyone explain to me why this is the case?
Upvotes: 0
Views: 58
Reputation: 1499770
You're printing out a java.util.Date
(the result of calling getTime()
). A Date
doesn't include time zone information at all - Date.toString()
always displays the point in time represented by that Date
in the default time zone.
Basically, you should avoid calling Date.toString()
- it's the cause of much confusion. Use a SimpleDateFormat
instead, which you can set to use a particular time zone.
Alternatively, use the java.time
classes if you're using Java 8, or Joda Time otherwise - both are much better options than java.util.Date
and java.util.Calendar
.
Upvotes: 2