Tobitor
Tobitor

Reputation: 1508

Groovy: How to get unix time of a certain date instead of current Date?

I have this code:

Date toDate = new Date();
Date fromDate = toDate - 30
long unixToTime = currentDate.getTime() / 1000
long unixFromDate = fromDate.getTime() / 1000

With this code I get the unix Time for the current Date and the unix Time for a date 30 days before. What I instead want is to get a code, where I can enter a specific toDate (e.g. 31-12-2020, 10:00:00) and then get the unix time of this instead.

Note: I am an absolute beginner regarding groovy.

Upvotes: 0

Views: 803

Answers (1)

cfrick
cfrick

Reputation: 37043

Easy for manual input is the builder of from LocalDateTime. If you have many dates or they come from a different source, you might be better off to parse directly into Instant. From the Instant you can get the seconds since the epoch. E.g.

java.time.LocalDateTime.of(2020,2,24,16,42).toInstant(java.time.ZoneOffset.UTC).epochSecond
// → 1582562520

Upvotes: 2

Related Questions