-1

I have date and time in string format in one of my models. "startTime": "2022-10-19T14:31:22+00:00"

How can I convert it to long format in Java?

I tried using 'Long.valueOf(startTime)' and 'Long.parseLong(startTime)' are two functions.

but in both I am getting an exception.

"at the java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)" 
Raushan Kumar
  • 1,195
  • 12
  • 21
Ravi
  • 21
  • 5
  • 2
    Why is this tagged `spring-boot`? How are you receiving/working with `startTime`? – Sotirios Delimanolis Feb 05 '23 at 20:42
  • 1
    Hello @Ravi. Next time try to ask the question in Google like you did here. The first result would point you to https://stackoverflow.com/questions/12473550/how-to-convert-a-string-date-to-long-millseconds – gfelisberto Feb 05 '23 at 20:42
  • 1
    @gfelisberto Actually, [that](https://stackoverflow.com/questions/12473550/how-to-convert-a-string-date-to-long-millseconds) is not a good duplicate of this. The [Answer here](https://stackoverflow.com/a/75355402/642706) on this page is more appropriate, and briefer. – Basil Bourque Feb 05 '23 at 20:54

1 Answers1

5

You can parse your datetime format using builtin methods - also to convert it to a long value (assuming the number of seconds since the epoch).

Instant.parse("2022-10-19T14:31:22+00:00").getEpochSecond()

See https://docs.oracle.com/en/java/javase/19/docs/api/java.base/java/time/Instant.html

See code run at Ideone.com.

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
Queeg
  • 7,748
  • 1
  • 16
  • 42
  • Interesting. Instant doesn't say that it will parse an offset datetime but it seems it will – g00se Feb 05 '23 at 22:52
  • @g00se I too was surprised to find `Instant.parse` worked as well as using `OffsetDateTime.parse`. Worked with `+01:00` too. I vaguely recall this more flexible formatting being tolerated by `Instant.parse` in later versions, after the initial Java 8 release, but I'm not sure. – Basil Bourque Feb 06 '23 at 01:53
  • 1
    From Java SE 15 Javadoc for `Instant#parse()`: _"When parsing, the behaviour of `DateTimeFormatterBuilder.appendOffsetId()` will be used to parse the offset, converting the instant to UTC as necessary."_ – Jim Garrison Feb 06 '23 at 01:58
  • @JimGarrison I don't see that [here](https://docs.oracle.com/en/java/javase/15/docs/api/java.base/java/time/Instant.html#parse(java.lang.CharSequence)) – g00se Feb 06 '23 at 10:00
  • Sorry, it's in `DateTimeFormatter.ISO_INSTANT`, which is linked from `Instant#parse()`. – Jim Garrison Feb 07 '23 at 22:22