将Java字符串解析为GMT日期 [英] Parsing Java String into GMT Date

查看:529
本文介绍了将Java字符串解析为GMT日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to parse a String that represents a date using GMT, but it prints out in my timezone on my PC (pacific). When I run the below I get the below output. Any ideas on how to get the parse to parse and return a GMT date? If you look below I'm setting the timezone using format.setTimeZone(TimeZone.getTimeZone("GMT")); but its not producing the desired result.

从以下代码输出:

Mon Oct 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)); ,用于将字符串格式化为日期,即

You are using format.setTimeZone(TimeZone.getTimeZone("GMT")); in the formatter, which is being used in formatting the string into date i.e.

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

解析处理 2012-10-29T12:57:00-0000 是一个 GMT 值,但您正在打印 date ,它使用本地timezome打印因此您注意到差异。

is parsed treating 2012-10-29T12:57:00-0000 was a GMT value, but you are printing date which uses local timezome in printing hence you are noticing the difference.

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

If you want to print the date back in GMT, please use:

    String formattedDate = format.format(date);

并打印 formattedDate 这将是 GMT

and print the formattedDate. This will be GMT.

    System.out.println(formattedDate);

这篇关于将Java字符串解析为GMT日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆