Convert "2020-10-31T00:00:00Z" String Date to long

Justin :

I am having Input Date as "2020-10-31T00:00:00Z". i want to parse this Date to get Long milliseconds. Note: Converted milliseconds should be in Sydney Time (ie GMT+11).

FYI,

public static long RegoExpiryDateFormatter(String regoExpiryDate)
    {
        long epoch = 0;

        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
        df.setTimeZone(TimeZone.getTimeZone("GMT+11"));
        Date date;
        try {
            date = df.parse(regoExpiryDate);
            epoch = date.getTime();
        } catch (ParseException e) {
            System.out.println("Exception is:" + e.getMessage());
            e.printStackTrace();
        }

        System.out.println("Converted regoExpiryDate Timestamp*************** " + epoch);
        return epoch;
    }

Output: 1604062800000 which gives Date as 30/10/2019 by using Epoch Converter, but in input i'm passing 31st as Date. Can anyone please clarify this?

Sweeper :

By doing df.setTimeZone(TimeZone.getTimeZone("GMT+11"));, you are asking the date formatter to interpret your string in the GMT+11 time zone. However, your string shouldn't be interpreted in that timezone. See that Z in the string? That stands for the GMT time zone, so you should have done this instead:

df.setTimeZone(TimeZone.getTimeZone("GMT"));

In fact, your string is in the ISO 8601 format for an Instant (or a "point in time", if you prefer). Therefore, you could just parse it with Instant.parse, and get the number of milliseconds with toEpochMilli:

System.out.println(Instant.parse("2020-10-31T00:00:00Z").toEpochMilli());
// prints 1604102400000

Warning: you shouldn't really use SimpleDateFormat anymore if the Java 8 APIs (i.e. Instant and such) are available. Even if they are not, you should use NodaTime or something like that.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related