Here to Learn.
Here to Learn.

Reputation: 693

Unable to get the date in UTC format

I have written two functions - today() and todayUTC() - as:

public static Date today() {
  Calendar cal = Calendar.getInstance();
  return cal.getTime();
}

public static Date todayUTC() {
  Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
  return cal.getTime();
}

But when I print the results of these functions using:

public void todayTest() {
  Date date1 = OOTBFunctions.today();
  System.out.println("today: "+date1);

  Date dateUTC1 = OOTBFunctions.todayUTC();
  System.out.println("todayUTC: "+dateUTC1);
}

I saw that both statements print the same value i.e.

today: Thu Aug 30 14:48:56 PDT 2012
todayUTC: Thu Aug 30 14:48:56 PDT 2012

Can anybody suggest what am I missing in UTC function that I am getting local timezone date.

Upvotes: 0

Views: 152

Answers (2)

Aravind Yarram
Aravind Yarram

Reputation: 80192

Java uses the default Locale while printing and that is why you see that behavior. Use code like below to format and print it in the locale/format you want. Remember

  • When you create a Date object, it is always in UTC.
  • Display the date in the Locale of the user.
  • Store the date in UTC.

Code

final SimpleDateFormat sdf = new SimpleDateFormat("the format you want");
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
final String utcTime = sdf.format(new Date());

You doesn't need both today() and todayUTC() methods. keep and like below

public static Date nowInUTC() 
{
  return new Date();
}

You doesn't need to test anything.

Upvotes: 3

Jon Skeet
Jon Skeet

Reputation: 1503859

Both of your methods will return the same value - a Date object doesn't have any notion of a time zone (unlike a Calendar). A Date just represents an instant in time, stored internally as the number of milliseconds since midnight January 1st 1970, UTC. Effectively, you've got two methods which are equivalent to:

return new Date(System.currentTimeMillis());

Date.toString() always uses the system default time zone.

If you want to maintain a date/time with a time zone, consider just using Calendar. If you want to format a particular instant in time in a time zone, just use SimpleDateFormat having set the time zone.

Ideally, change to use Joda Time instead of Date or Calendar though - it's a much cleaner API.

Upvotes: 0

Related Questions