java - 如何将 java.util.Date 转换为 GMT 格式

标签 java

我有一个显示山区时区的字符串“2014-07-02T17:12:36.488-01:00”。我将其解析为 java.util.date 格式。现在我需要将其转换为 GMT 格式。谁能帮帮我??

  SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
    Object dd = null;
    try {
         dd=sdf.parseObject("2014-07-02T17:12:36.488-01:00");
        System.out.println(dd);
    } catch (ParseException e) {
        e.printStackTrace();`enter code here`
    }
    SimpleDateFormat gmtDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    gmtDateFormat.setTimeZone(java.util.TimeZone.getTimeZone("GMT"));
System.out.println("Current Date and Time in GMT time zone:+ gmtDateFormat.format(dd));

最佳答案

您的代码中存在一些问题。例如,格式字符串与您正在解析的字符串的实际格式不匹配。

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSX");
Object dd = null;
try {
    dd = sdf.parse("2014-07-02T17:12:36.488-01:00");
    System.out.println(dd);
} catch (ParseException e) {
    e.printStackTrace();
}

SimpleDateFormat gmtDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ssX");
gmtDateFormat.setTimeZone(java.util.TimeZone.getTimeZone("GMT"));

System.out.println("Current Date and Time in GMT time zone:" + gmtDateFormat.format(dd));

要以您喜欢的任何时区打印当前日期,请在 SimpleDateFormat 对象上设置您要使用的时区。例如:

// Create a Date object set to the current date and time
Date now = new Date();

DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSX");
df.setTimeZone(TimeZone.getTimeZone("GMT"));
System.out.println("Current date and time in GMT: " + df.format(now));

df.setTimeZone(TimeZone.getTimeZone("IST"));
System.out.println("Current date and time in IST: " + df.format(now));

关于java - 如何将 java.util.Date 转换为 GMT 格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24533484/

相关文章:

java - 运行 Storm 拓扑时为 "java.lang.OutOfMemoryError: unable to create new native thread"

java - 为每个 Controller 中的每个操作设置模型属性

java - 从cli启动并杀死hadoop任务

java - 如何在树中找到选定的节点?

java解码base64字符串

java - NumberFormat API 说明

java - GoogleAuthUtil/GoogleAccountCredential 1.17.0-rc SDK 1.8.8 API 19 不适用于 Android 中的 google 端点

java - 如何在 Eclipse 中为 Java 匿名方法设置代码格式化程序

java - 如何通过复合对象属性查找?

java - 如何为 Fragment 中包含的 ListView 调用 setListAdapter