-2

I have a string "2019-10-11T04:56:06.000Z", how to convert it to timestamp in Java.

linrongbin
  • 2,967
  • 6
  • 31
  • 59
  • 1
    Start with [Instant.parse(CharSequence)](https://docs.oracle.com/javase/8/docs/api/java/time/Instant.html#parse-java.lang.CharSequence-) – dnault Oct 15 '19 at 05:00
  • Do you want you timestamp on any particular form? You may say that your string *is* already a timestamp, but of course you should prefer an `Instant` object over a string. – Ole V.V. Oct 15 '19 at 08:47

1 Answers1

0

You first convert the string to a date (java.util.Date) using the parse method of the SimpleDataFormat class. After, from the date object you can get the timestamp.

    String strDate = "2019-10-11T04:56:06.000Z";
    try {
        Date date=new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS").parse(strDate);
        long timestamp = date.getTime();
    } catch (ParseException e) {
        e.printStackTrace();
    } 
  • You should not use `SimpleDateFormat`. That class is notoriously troublesome and long outdated. As @dnault said, use the modern `Instant` class. It's also simpler and easier. Furthermore the code in this answer gives a wrong result on the majority of JVMs. This is part of the trouble with `SimpleDateFormat`. – Ole V.V. Oct 15 '19 at 08:42