将日期字符串转换为UTC

时间:2019-11-26 10:49:47

标签: java spring spring-boot cassandra

我想将存储为String的日期转换为UTC

String date = "Fri Aug 19 22:30:00 IST 2019"(我是从Cassandra获取)。 您如何将其转换为这种格式? "2019-08-19T17:00:00+00:00"

2 个答案:

答案 0 :(得分:0)

通常,以下代码可用于转换并显示2019-04-01T11:05:30Z[GMT]

    val formatter = DateTimeFormatter.ofPattern("E, d MMM yyyy HH:mm:ss z")
    val dateTime = ZonedDateTime.parse("Mon, 1 Apr 2019 11:05:30 GMT", formatter)
    println(dateTime)

如果预定义了区域IST,则还可以在字符串中进行一些操作并删除该区域,然后执行以下操作,这还将打印2019-08-19T17:00Z[GMT]

    val str = "Mon Aug 19 22:30:00 2019"
    val formatter = DateTimeFormatter.ofPattern("EEE MMM dd HH:mm:ss yyyy")
    val dateTime = LocalDateTime.parse(str, formatter)
    val zdtAtAsia = dateTime.atZone(ZoneId.of("Asia/Kolkata"))
    val zdtAtGmt = zdtAtAsia.withZoneSameInstant(ZoneId.of("GMT"))

(示例在kotlin中。但是它使用与Java相同的库)

答案 1 :(得分:0)

  @Test
  void test() {
    String date = "Mon Aug 19 22:30:00 IST 2019";
    DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("E MMM dd HH:mm:ss z yyyy");
    ZonedDateTime formatDateTime = ZonedDateTime.parse(date, dateTimeFormatter)
                                                .withZoneSameLocal(
                                                    ZoneId.of("UTC"));
    System.out.println(formatDateTime);
  }

// Output: 2019-08-19T22:30Z[UTC]

The date mentioned in the post is wrong and it will end up in 
"java.time.format.DateTimeParseException: Text 'Fri Aug 19 22:30:00 IST 2019' could not be parsed: Conflict found: Field DayOfWeek 1 differs from DayOfWeek 5 derived from 2019-08-19"