Reputation: 127
I am trying following piece of code using the Java Calendar API
class TimeIssue
{
public void showUTCTime(long millis, final String msg)
{
Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
cal.setTimeInMillis(0);
System.out.println(msg + "(UTC):" + cal.getTime());
}
public void showLocalTime(long millis, final String msg)
{
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(0);
System.out.println(msg + "(LOCAL):" + cal.getTime());
}
public static void main(String[] args)
{
long epochSec = 0;
TimeIssue obj = new TimeIssue();
obj.showUTCTime(epochSec, "EPOCH");
obj.showLocalTime(epochSec, "EPOCH");
}
}
When I execute this program, I get the output as ( My Time Zone is GMT+5:30)
EPOCH(UTC):Thu Jan 01 05:30:00 IST 1970
EPOCH(LOCAL):Thu Jan 01 05:30:00 IST 1970
I have 2 concerns here
Could you please suggest what am I missing here ?
Abhishek
Upvotes: 0
Views: 1432
Reputation: 340200
The accepted answer is correct.
java.util.Date
Working with date-time and time zones is much easier if you use a competent library. The java.util.Date and .Calendar classes are notoriously troublesome. Use either Joda-Time or the java.time package in Java 8 (inspired by Joda-Time).
Example code in Joda-Time 2.5. We instantiate a pair of DateTime objects that represent the same moment in the timeline of the Universe but as seen from two different wall-clock-times (UTC and India).
DateTime dateTimeUtc = new DateTime( 0, DateTimeZone.UTC );
DateTimeZone timeZoneKolkata = DateTimeZone.forID( "Asia/Kolkata" );
DateTime dateTimeKolkata = dateTimeUtc.withZone( timeZoneKolkata );
Upvotes: 0
Reputation: 213401
The Calendar.getTime()
method returns the Date
object, which is just the number of milliseconds since epoch. Printing that instance invokes the Date#toString()
method, which uses the system default timezone to format the date. Giving the Calendar instance a timezone, doesn't associate the resultant Date
object with that timezone. In fact, Date
object has no concept of timezones.
What you want is to format the date yourself using DateFormat
, and set the timezone in that. Change your UTC
method to this:
public void showUTCTime(long millis, final String msg) {
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(0);
DateFormat dateFormat = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy");
dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
System.out.println(msg + "(UTC):" + dateFormat.format(cal.getTime()));
}
Upvotes: 3
Reputation: 915
The problem is that you're setting the time zone by calling obj.showUTCTime(epochSec, "EPOCH");
and it's saved after this. You need to set it again in showLocalTime
to have the other time displayed in another time zone.
The first line of output is UTC 00:00:00 1970 in your time zone, that is 5:30
Upvotes: 0