0

I am pulling data from an API, and one of the pieces of data I get is a date and time. The date and time is returned in a string format and I need to get that in to a Unix Timestamp for my mySQL database.

The String looks like: "2018-10-23 18:00:00"

Does anyone know how I would go about getting that from a String to a Unix Timestamp? Should I try using java.util.Date?

halfer
  • 19,824
  • 17
  • 99
  • 186
Fletchy
  • 311
  • 1
  • 4
  • 18
  • 1
    No, don’t use `Date`, it’s long outdated. You need to know in which time zone or at which offset to interpret the string you pull. Then use `LocalDateTime`, `DateTimeFormatter` and a conversion via `ZonedDateTime` or `OffsetDateTime`. Those classes have a ´toEpochSecond` method that will give you Unix time. – Ole V.V. Oct 23 '18 at 19:05
  • 1
    Search and find. This question has been asked and answered many times before. Just avoid the answers recommending `Date` and/or `SimpleDateFormat`. Those are the outdated and poorly designed ones. I recommend for example [this answer to the linked question](https://stackoverflow.com/a/45756848/5772882). – Ole V.V. Oct 23 '18 at 19:18
  • General question to continue off this topic, it may seem silly but I guess I just want clarification/validation here. Does a Unix Timestamp include Date and Time in its value? – Fletchy Oct 23 '18 at 20:15
  • 1
    No, a [Unix timestamp](https://en.wikipedia.org/wiki/Unix_time) is the number of seconds since January 1, 1970 at 00:00 UTC. The current Unix time is 1 540 357 615. Again, your search engine would have found thia piece of information faster than I can type it. – Ole V.V. Oct 24 '18 at 05:07

1 Answers1

1

Similar to this

Convert a date format in epoch

but change

SimpleDateFormat df = new SimpleDateFormat("MMM dd yyyy HH:mm:ss.SSS zzz");

to

SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Toan Le
  • 412
  • 1
  • 6
  • 17
  • 2
    Please don’t teach the young ones to use the long outdated and notoriously troublesome `SimpleDateFormat` class. At least not as the first option. And not without any reservation. Today we have so much better in [`java.time`, the modern Java date and time API](https://docs.oracle.com/javase/tutorial/datetime/) and its `DateTimeFormatter`. – Ole V.V. Oct 23 '18 at 19:04