Convert Date/Time for given Timezone - java

travega picture travega · Oct 6, 2011 · Viewed 339.7k times · Source

I want to convert this GMT time stamp to GMT+13:

2011-10-06 03:35:05

I have tried about 100 different combinations of DateFormat, TimeZone, Date, GregorianCalendar etc. to try to do this VERY basic task.

This code does what I want for the CURRENT TIME:

Calendar calendar = new GregorianCalendar(TimeZone.getTimeZone("GMT"));

DateFormat formatter = new SimpleDateFormat("dd MMM yyyy HH:mm:ss z");    
formatter.setTimeZone(TimeZone.getTimeZone("GMT+13"));  

String newZealandTime = formatter.format(calendar.getTime());

But what I want is to set the time rather than using the current time.

I found that anytime I try to set the time like this:

calendar.setTime(new Date(1317816735000L));

the local machine's TimeZone is used. Why is that? I know that when "new Date()" returns UTC+0 time so why when you set the Time in milliseconds does it no longer assume the time is in UTC?

Is it possible to:

  1. Set the time on an object (Calendar/Date/TimeStamp)
  2. (Possibly) Set the TimeZone of the initial time stamp (calendar.setTimeZone(...))
  3. Format the time stamp with a new TimeZone (formatter.setTimeZone(...)))
  4. Return a string with new time zone time. (formatter.format(calendar.getTime()))

Thanks in advance for any help :D

Answer

Charleston picture Charleston · Mar 12, 2014

For me, the simplest way to do that is:

Calendar calendar = Calendar.getInstance();
calendar.setTime(new Date());
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");

//Here you say to java the initial timezone. This is the secret
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
//Will print in UTC
System.out.println(sdf.format(calendar.getTime()));    

//Here you set to your timezone
sdf.setTimeZone(TimeZone.getDefault());
//Will print on your default Timezone
System.out.println(sdf.format(calendar.getTime()));