Reputation: 99
How can I use Groovy to extract just seconds from a java.sql.Timestamp
?
I have used the following code to extract the time
def time = new Timestamp(System.currentTimeMillis())
This gives me the following output:
2018-01-24 13:56:19.444
It would be helpful if I get just the seconds and nanos (19.444).
I am developing a Groovy script to make a difference between my default timer(sec) and real time in sec.
Upvotes: 0
Views: 470
Reputation: 171114
That's milliseconds, not nanoseconds. Another way to get it (assuming you want it in a double
, and assuming you are using Java 8), would be via the java.time
classes:
import java.sql.Timestamp
import java.time.temporal.ChronoField
import java.time.temporal.ChronoUnit
import java.time.temporal.TemporalField
// I assume this comes from a database
def time = new Timestamp(System.currentTimeMillis())
double secondsAndMillis = time.toInstant().with { instant ->
instant.truncatedTo(ChronoUnit.MINUTES).until(instant, ChronoUnit.MILLIS) / 1000d
}
Upvotes: 0
Reputation: 3016
You already have all to do it:
def time = new java.sql.Timestamp(System.currentTimeMillis())
println "${time.seconds}.${time.nanos}"
Upvotes: 1