如何在Java中解析字符串为Date

问题描述 投票:0回答:1

我想将字符串24 May 2020 07:40 AM转换为日期格式Mon May 24 07:40:55 IST 2020。我尝试使用Calendar和SimpleDateFormatter,但没有找到解决方案。任何帮助表示赞赏。

我希望返回类型为Date,因为我必须将其与几个Date进行比较。

java date datetime date-format date-formatting
1个回答
0
投票

java.time

[当您有一些Date对象时-可能是从您现在无法升级到java.time的旧API中获得的-我仍然建议您将java.time(现代Java日期和时间API)用于您的比较。

在下面的示例中,我使用java.time中的Instant,但您也可以使用ZonedDateTime或其他一些现代类型。

    DateTimeFormatter fromFormatter = DateTimeFormatter.ofPattern("d MMM uuuu hh:mm a", Locale.ENGLISH);

    Date anOldfashionedDate = new Date(1_590_286_000_000L);
    Date anotherOldfashionedDate = new Date(1_590_287_000_000L);
    System.out.println("The Date objects are " + anOldfashionedDate + " and " + anotherOldfashionedDate);

    String aString = "24 May 2020 07:40 AM";

    Instant instantFromDate = anOldfashionedDate.toInstant();
    Instant instantFromAnotherDate = anotherOldfashionedDate.toInstant();
    Instant instantFromString = LocalDateTime.parse(aString, fromFormatter)
            .atZone(ZoneId.of("Asia/Kolkata"))
            .toInstant();

    System.out.println("Comparing " + instantFromDate + " and " + instantFromString + ": "
            + instantFromDate.compareTo(instantFromString));
    System.out.println("Comparing " + instantFromAnotherDate + " and " + instantFromString + ": "
            + instantFromAnotherDate.compareTo(instantFromString));

输出是((在亚洲/加尔各答时区运行):

The Date objects are Sun May 24 07:36:40 IST 2020 and Sun May 24 07:53:20 IST 2020
Comparing 2020-05-24T02:06:40Z and 2020-05-24T02:10:00Z: -1
Comparing 2020-05-24T02:23:20Z and 2020-05-24T02:10:00Z: 1

Instant以UTC打印;这就是它的toString方法生成的。尾随的Z表示UTC。由于印度标准时间比世界标准时间早5小时30分钟,因此印度的上午7:40与世界标准时间的02:10相同。

鉴于您现在着手使用java.time,因此,有一天,您的旧版API也将升级为使用java.time,您已经做好了充分的准备。

相反的转换

如果您确实坚持使用Date,按照要求回答您的问题,相反的转换也很容易:

    Date oldfashionedDateFromInstantFromString = Date.from(instantFromString);
    System.out.println("Converting to old-fashoined: " + oldfashionedDateFromInstantFromString);

转换为老式的:IST 2020年5月24日星期日,07:40:00

链接

Oracle tutorial: Date Time解释如何使用java.time。

© www.soinside.com 2019 - 2024. All rights reserved.