Search code examples
groovy

Get Epoch of midnight of current date - Groovy


I have a scheduler job that needs to pick records that are updated since beginning till yesterday (before 12AM of today). Records that are updated today should not be picked.

I wrote the below logic. But this logic considers records that are updated before the current time and not the current date. Which means, records that are updated today before the current time are being picked too.

Please help fix this.

Date today = new Date()
println (lastDay.getTime().toString())

Note: Need to frame epoch for current date midnight 12 AM


Solution

  • Assuming you mean midnight in your timezone, you can do this to get the epoch in milliseconds:

    import java.time.*
    import java.time.temporal.*
    
    long epochMillisecondsAtMidnightToday = ZonedDateTime.now().truncatedTo(ChronoUnit.DAYS).toInstant().toEpochMilli()