将日期字符串转换为utc

pn9klfpd  于 2021-06-10  发布在  Cassandra
关注(0)|答案(2)|浏览(527)

我想转换存储为 StringUTC . String date = "Fri Aug 19 22:30:00 IST 2019" (这是我从Cassandra那里得到的)。你怎么把它转换成这种格式? "2019-08-19T17:00:00+00:00"

cedebl8k

cedebl8k1#

@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"
niknxzdl

niknxzdl2#

通常,下面的代码用于转换和打印 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相同的库)

相关问题