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;