Home > Blockchain >  JAVA - Parse String date to long
JAVA - Parse String date to long

Time:10-17

2024-01-01T00:00:00.000Z

I would like to get this String in ms(long) I tried:

long res = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ").parse(createdAt).getTime();

but it doesn't work.

CodePudding user response:

java.time

The java.util Date-Time API and their formatting API, SimpleDateFormat are outdated and error-prone. It is recommended to stop using them completely and switch to the modern Date-Time API*.

Solution using java.time, the modern Date-Time API:

import java.time.Instant;

public class Main {
    public static void main(String[] args) {
        long res = Instant.parse("2024-01-01T00:00:00.000Z").toEpochMilli();
        System.out.println(res);
    }
}

Output:

1704067200000

ONLINE DEMO

Note that the modern Date-Time API is based on ISO 8601 and does not require using a DateTimeFormatter object explicitly as long as the Date-Time string conforms to the ISO 8601 standards.

Learn more about the modern Date-Time API from Trail: Date Time.

For any reason, if you want to use SimpleDateFormat:

Use the following format:

yyyy-MM-dd'T'HH:mm:ss.SSSXXX

Check the SimpleDateFormat documentation to understand the difference between Z and X.


* If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8 APIs available through desugaring. Note that Android 8.0 Oreo already provides support for java.time.

  • Related