将Java字符串解析为GMT日期

我正在尝试使用GMT解析表示日期的字符串,但它会在我的PC上(太平洋)打印出我的时区。 当我运行以下时,我得到以下输出。 关于如何解析解析并返回GMT日期的任何想法? 如果你看下面我使用format.setTimeZone设置时区(TimeZone.getTimeZone(“GMT”)); 但它没有产生预期的结果。

以下代码输出:

星期一10月29日05:57:00 PDT 2012

package javaapplication1; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.TimeZone; public class JavaApplication1 { public static void main(String[] args) throws ParseException { SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ"); format.setTimeZone(TimeZone.getTimeZone("GMT")); System.out.println(format.parse("2012-10-29T12:57:00-0000")); } } 

您正在使用format.setTimeZone(TimeZone.getTimeZone("GMT")); 在格式化程序中,用于将字符串格式化为日期,即

  Date date = format.parse("2012-10-29T12:57:00-0000"); 

解析2012-10-29T12:57:00-0000是一个GMT值, 但是你打印的date在打印中使用了本地timezome,因此你注意到了差异。

如果您想以GMT打印日期,请使用:

  String formattedDate = format.format(date); 

并打印formattedDate这将是GMT

  System.out.println(formattedDate); 
 System.out.println(format.parse("2012-10-29T12:57:00-0000")); 

将日期解析为GMT并返回Date对象。 然后将其打印出来(使用默认的toString() – 方法)。 这只是使用您的计算机的设置。 所以你应该使用:

 Date parsedDate=format.parse("2012-10-29T12:57:00-0000"); System.out.println(format.format(parsedDate)); 

完整的工作示例

 import java.text.SimpleDateFormat; import java.util.Date; import java.util.Locale; import java.util.TimeZone; public class Main { public static void main(String[] args) { final SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy hh:mm:ss z", Locale.ENGLISH); sdf.setTimeZone(TimeZone.getTimeZone("UTC")); System.out.println(sdf.format(new Date())); // ^^^ note printing the results of sdf.format() // not a raw `Date` } } 

结果: 31-10-2012 08:32:01 UTC 请注意我实际打印出来的内容!

尝试这个,

 public static String converterGMTToLocal(String datahora_gmt) { try { SimpleDateFormat fmt = new SimpleDateFormat("YYYY-MM-dd HH:mm"); Calendar cal = Calendar.getInstance(); cal.setTime(fmt.parse(datahora_gmt)); cal.add(Calendar.HOUR, -3); return fmt.format(cal.getTime()); } catch (ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); return e.getMessage(); } } 

更改项目的值…进行适当的更改