如何在UTC 7中将UTC偏移的日期时间值转换为GMT

GOP*_*OPI 6 java datetime utc date-conversion gmt

我的日期时间值为2016-12-21T07:48:36,偏移量为UTC + 14.如何将日期时间转换为等效的标准GMT时间.

我尝试使用sampleDateFormat.parse()method.But,我无法获得UTC偏移量的TimeZone对象.

sampleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC+14:00"))
Run Code Online (Sandbox Code Playgroud)

请帮我在Java 7中将UTC日期时间转换为标准GMT时间.

Gro*_*uez 2

我假设您将原始日期作为字符串。请执行下列操作:

  • 创建一个SimpleDateFormat并将时区设置为“GMT+14”
  • 解析字符串值。你得到一个Date对象
  • 将时区设置SimpleDateFormat为“UTC”(或使用不同的SimpleDateFormat实例)
  • 设置日期格式(如果您也希望结果为字符串)

例子:

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;

public class ConvertToUTC {
  public static void main(String[] args) throws Exception {

      String dateval = "2016-12-21T07:48:36";
      DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
      df.setTimeZone(TimeZone.getTimeZone("GMT+14"));
      Date date = df.parse(dateval);

      System.out.println(df.format(date)); // GMT+14

      df.setTimeZone(TimeZone.getTimeZone("UTC"));
      System.out.println(df.format(date)); // UTC
  }
}
Run Code Online (Sandbox Code Playgroud)