首页 > 解决方案 > 如何将字符串日期解析为其他时区的其他日期

问题描述

鉴于我有这样的字符串日期

val date =  "2019-01-07T13:54:00+0000"

如何将此日期解析为其他时区,例如“亚洲/加尔各答”?

我在尝试:

val zone = DateTimeZone.forID("Asia/Kolkata")

val resultMillis = ISODateTimeFormat
    .dateTimeParser()
    .withZone(zone)
    .parseDateTime(date)

但它没有奏效

标签: androiddatetimekotlinjodatimeandroid-jodatime

解决方案


这是一个两步过程:解析到字符串中的偏移量或时区,然后转换为所需的时区。我只会写 Java 代码,我相信你会翻译:

    DateTimeZone zone = DateTimeZone.forID("Asia/Kolkata");
    String date = "2019-01-07T13:54:00+0000";
    DateTime dt = ISODateTimeFormat.dateTimeParser()
            .parseDateTime(date)
            .withZone(zone);
    System.out.println(dt);

输出是:

2019-01-07T19:24:00.000+05:30

你快到了。我在文本上只是将呼叫交换为withZoneand parseDateTime


推荐阅读