Skip to content

Instantly share code, notes, and snippets.

@arkival
Last active February 20, 2018 02:44
Show Gist options
  • Save arkival/50905b2bbe7ee51d8742cdc5fde454ec to your computer and use it in GitHub Desktop.
Save arkival/50905b2bbe7ee51d8742cdc5fde454ec to your computer and use it in GitHub Desktop.

Easy timestamps with java.time

Java 8 introduced the java.time package which makes short work of creating and parsing timestamps.

To create a String representation of a timestamp we can use LocalDateTime.now().toString(), e.g.

String ts = LocalDateTime.now().toString()

To convert the string back into a time object we can use the parse method of LocalDateTime, e.g.

LocalDateTime start = LocalDateTime.parse(ts)

If we have two LocalDateTime objects, start and stop then we can determine the number of seconds between them using the ChronoUnit class, e.g.,

long elapsedSeconds=ChronoUnit.SECONDS.between(start,stop)

Don't forget to include the appropriate imports.

import java.time.*;
import java.time.temporal.ChronoUnit;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment