Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SimpleDateFormat parse loses timezone [duplicate]

Code:

 SimpleDateFormat sdf = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss z");     sdf.setTimeZone(TimeZone.getTimeZone("GMT"));     System.out.println(new Date());     try {         String d = sdf.format(new Date());         System.out.println(d);         System.out.println(sdf.parse(d));     } catch (Exception e) {         e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.     } 

Output:

Thu Aug 08 17:26:32 GMT+08:00 2013 2013.08.08 09:26:32 GMT Thu Aug 08 17:26:32 GMT+08:00 2013 

Note that format() formats the Date correctly to GMT, but parse() lost the GMT details. I know I can use substring() and work around this, but what is the reason underlying this phenomenon?

Here is a duplicate question which doesn't have any answers.

Edit: Let me put the question in another way, what is the way to retrieve a Date object so that its always in GMT?

like image 608
Achow Avatar asked Aug 08 '13 09:08

Achow


1 Answers

All I needed was this :

SimpleDateFormat sdf = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss"); sdf.setTimeZone(TimeZone.getTimeZone("GMT"));  SimpleDateFormat sdfLocal = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss");  try {     String d = sdf.format(new Date());     System.out.println(d);     System.out.println(sdfLocal.parse(d)); } catch (Exception e) {     e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates. } 

Output : slightly dubious, but I want only the date to be consistent

2013.08.08 11:01:08 Thu Aug 08 11:01:08 GMT+08:00 2013 
like image 170
Achow Avatar answered Sep 23 '22 07:09

Achow