如何将本地时间转换为 GMT?

4

我有一个字符串日期,格式如下:

2020-05-19 10:46:09 this is Asia/Jakarta time

我想将其转换为GMT时间,这是我的代码:

String created = New_tradingHistory_trade.getCreated_at();
                    Date date1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(created);
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
                    String CreatedGMT = sdf.format(date1);
                    System.out.print(CreatedGMT);

我收到的一直都是:

2020年5月19日10:46:09,我的问题是如何将我的日期转换为GMT?

1个回答

5

你应该使用 java-8日期时间API,停止使用遗留的DateSimpleDateFormat

  1. 你拥有的输入字符串是本地日期时间
  2. 因此,使用DateTimeFormatter将其解析为LocalDateTime
  3. 然后将localDateTime转换为在时区Asia/Jakarta下的ZoneDateTime
  4. 最后将zoneDateTime转换为等于UTCGTM日期时间
String input = "2020-05-19 10:46:09";

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

LocalDateTime localDateTime = LocalDateTime.parse(input,formatter);

ZonedDateTime zoneDateTime = localDateTime.atZone(ZoneId.of("Asia/Jakarta"));

System.out.println(zoneDateTime);

ZonedDateTime gmtDateTime = zoneDateTime.withZoneSameInstant(ZoneOffset.UTC);

System.out.println(gmtDateTime);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接