I had this function that convert string type of date to unix timestamp, how to convert the result to timeInSeconds and offsetInNanos
DateTimeFormatter formatter = DateTimeFormatter.ofPattern( "yyyy-MM-dd-HH-mm-ss"); String dateTimeString = "2016-06-21-10-19-22"; LocalDate date = LocalDate.parse(dateTimeString, formatter); ZonedDateTime resultado = date.atStartOfDay(ZoneId.of("UTC")); Instant i = resultado.toInstant(); long timeInSeconds = i.getEpochSecond(); int nanoAdjustment = i.getNano(); System.out.println("" + timeInSeconds + " seconds " + nanoAdjustment + " nanoseconds"); result is 1466467200 seconds 0 nanoseconds but the correct answer seems to be 1466504362 seconds
Advertisement
Answer
Edit
result is 1466467200 seconds 0 nanoseconds but the correct answer seems to be 1466504362 secondsI think it convert “2016-06-21-10-19-22” to 2016-06-21T00:00:00+00:00, how to solve this problem, to convert both date with time and date without time to correct timeInSeconds?
You are absolutely correct, that is what it does, This is because in your new code in the question you are
- Only parsing the date part. You are parsing into a
LocalDate
, which is a date without time of day, so the time of day in the string is being ignored. - Then calling
atStartOfDay()
. This makes sure that the time of day is set to — as the method name says — the start of the day, in this case in UTC, so 00:00:00 UTC.
To solve: instead parse into a LocalDateTime
so you get both date and time.
LocalDateTime date = LocalDateTime.parse(dateTimeString, formatter); OffsetDateTime resultado = date.atOffset(ZoneOffset.UTC);
The rest of the code is the same. Now the output is:
1466504362 seconds 0 nanoseconds
This is the result you said you expected. While a ZonedDateTime
would have worked too, for UTC it’s overkill, I recommend you use OffsetDateTime
as I am showing.
For how to parse a string that may or may not have time of day in it, see some of the questions that I link to at the bottom.
Original answer: java.time
I suppose that by offset in nanos you meant nano adjustment, nanosecond part or nano of second (not offset from UTC). With java.time, the modern Java date and time API, it’s straightforward:
DateTimeFormatter formatter = DateTimeFormatter.ofPattern( "MMM dd yyyy HH:mm:ss.SSS zzz", Locale.ENGLISH); String dateTimeString = "Jun 13 2003 23:11:52.454 UTC"; Instant i = ZonedDateTime.parse(dateTimeString, formatter) .toInstant(); long timeInSeconds = i.getEpochSecond(); int nanoAdjustment = i.getNano(); System.out.println("" + timeInSeconds + " seconds " + nanoAdjustment + " nanoseconds");
Output is:
1055545912 seconds 454000000 nanoseconds
I just did what deHaar said in the comments.
Links
- Oracle tutorial: Date Time explaining how to use java.time.
- Questions on parsing dates with and without times: