-2

I am receiving a string in ISO 8601 date-time format 2020-11-03T15:23:24.388Z. What is the best way to convert this into epoch seconds in Java?

Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
Hoya Coder
  • 41
  • 5
  • That format is the ISO 8601 date-time format. – VGR Oct 04 '20 at 15:53
  • 1
    SideNote: If you convert in epoch seconds then the millisecond part will be excluded. – Eklavya Oct 04 '20 at 15:57
  • 1
    @ArvindKumarAvinash I was disappointed myself that I didn’t find better matching original questions. They must be there, mustn’t they? Still I found it more helpful to close as a duplicate with links to some questions that can get you most of the way than to close as a no-effort requirement dump without any links, though you may argue that the latter would be more correct. – Ole V.V. Oct 04 '20 at 18:09
  • 1
    Also @ArvindKumarAvinash, by all means do challenge me. I consider questions of originals and duplicates highly opinion-besed. A guru — thanks for the nice word — who doesn’t stand being challenged can be no real guru. And nobody makes the correct judgement every time. – Ole V.V. Oct 04 '20 at 18:18
  • 1
    Hoya Coder, I believe we should have said this before discussing whether your questions is a duplicate: It’s a poor question by Stack Overflow standards. And yes, we’re picky, and I hope you’ll forgive that I’m direct. You’re supposed to search for an answer first, and you’re likely to find one faster than we can write a new one. When asking you’re supposed to report what your search brought up and how it failed to answer your question or what more precisely you are still missing. Please go through [How do I ask a good question?](https://stackoverflow.com/help/how-to-ask) once more. – Ole V.V. Oct 05 '20 at 03:57
  • That said, Hoya Coder, your opinion on whether your question is a duplicate and to what extent the linked original questions do or don’t answer your question, is welcome too. – Ole V.V. Oct 05 '20 at 04:01
  • 1
    @ArvindKumarAvinash I think I found a couple of more helpful previous questions, so I have edited the list of origianls. Thanks for putting a light pressure on me for doing that. – Ole V.V. Oct 05 '20 at 04:08

1 Answers1

6

Using the modern date-time API, you can do it as shown below:

import java.time.Instant;

public class Main {
    public static void main(String[] args) {
        Instant instant = Instant.parse("2020-11-03T15:23:24.388Z");
        long seconds = instant.getEpochSecond();
        System.out.println(seconds);
    }
}

Output:

1604417004

If you are doing it for your Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring and How to use ThreeTenABP in Android Project.

Learn more about the modern date-time API at Trail: Date Time.

Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110