简体   繁体   中英

How to parse String to Date in Java

I want to convert a String 24 May 2020 07:40 AM to date format Mon May 24 07:40:55 IST 2020 . I tried using Calendar and SimpleDateFormatter but didn't find a solution. Any help is appreciated.

I want the return type to be Date since I have to compare it with a couple of Date s.

java.time

When you've got some Date objects — likely from a legacy API that you cannot afford to upgrade to java.time just now — I still recommend that you use java.time, the modern Java date and time API, for your comparisons.

In the following example I am using Instant from java.time, but you may use ZonedDateTime or some other modern type too.

    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));

Output is (when running in Asia/Kolkata time zone):

 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

An Instant prints in UTC; this is what its toString method generates. The trailing Z means UTC. Since India Standard Time is 5 hours 30 minutes ahead of UTC, 07:40 AM in India is the same time as 02:10 in UTC.

Given that you embark on using java.time now, you are well prepared when one day your legacy API gets upgraded to using java.time too.

The opposite conversion

If you do insist on using Date , to answer your question as asked, the opposite conversion is easy too:

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

Converting to old-fashioned: Sun May 24 07:40:00 IST 2020

Link

Oracle tutorial: Date Time explaining how to use java.time.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM