Convert given time to GMT
I had tried to convert the开发者_运维百科 given date Mon Jul 04 00:00:00 IST 2011
to GMT like this: 2011-07-04 18:10:47 GMT+00:00 2011
but it displays 3/7/11 6:30 PM
This is my code:
java.text.SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
java.text.SimpleDateFormat res_format = new SimpleDateFormat("dd/mm/yyyy HH:mm");
java.util.Date date1 = format.parse("2011-07-04 00:00:00");
DateFormat gmtFormat = new SimpleDateFormat();
TimeZone gmtTime = TimeZone.getTimeZone("GMT+00");
gmtFormat.setTimeZone(gmtTime);
System.out.println("Current Time: "+date1);
System.out.println("Time:"+gmtFormat.format(date1));
This works for me:
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.TimeZone;
public class TZ {
public static void main(String[] args) throws ParseException {
java.text.SimpleDateFormat sourceFormat = new SimpleDateFormat("EEE MMM dd HH:mm:ss ZZZ yyyy");
java.text.SimpleDateFormat gmtFormat = new SimpleDateFormat("yyyy-mm-dd HH:mm:ss zzzz");
java.util.Date date1 = sourceFormat.parse("Mon Jul 04 00:00:00 IST 2011");
TimeZone gmtTime = TimeZone.getTimeZone("GMT+00");
gmtFormat.setTimeZone(gmtTime);
System.out.println("Source date: " + date1);
System.out.println("gmt:" + gmtFormat.format(date1));
}
}
Quick solution with minimal change in your code is to replace:
DateFormat gmtFormat = new SimpleDateFormat();
To:
SimpleDateFormat gmtFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss z");
Your idea is correct. If you had bothered to look into the code once more, you would have known what you have done wrong.
Your code is working fine. But you don't see what you want because you have (most likely) initialized
java.text.SimpleDateFormat res_format = new SimpleDateFormat("dd/mm/yyyy HH:mm");
for the output
and you use a brand new SimpleDateFormat
, out of the blue to set the timezone and display.
If you change
DateFormat gmtFormat = new SimpleDateFormat();
to
java.text.SimpleDateFormat gmtFormat = new SimpleDateFormat("dd/MM/yyyy HH:mm zz");
You get what you want.
(Note the change in the format as well. It is dd/MM/yyyy
and not dd/mm/yyyy
)
You code would have been a lot more easier to read (for you, and others) if you had logically grouped the blocks, and not used fully qualified names for (almost) all classes
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = format.parse("2011-07-04 00:00:00");
SimpleDateFormat gmtFormat = new SimpleDateFormat("dd/MM/yyyy HH:mm zz");
TimeZone gmtTime = TimeZone.getTimeZone("GMT+00");
gmtFormat.setTimeZone(gmtTime);
System.out.println("Current Time: " + date);
System.out.println("Time:" + gmtFormat.format(date));
精彩评论