By Alvin Alexander. Last updated: July 15, 2024
As a brief note today, here’s a Scala function to get the Unix epoch time for X days ago (5 days ago, 10 days ago, etc.):
/**
* Returns a 10-digit Long (like 1585275929) representing the date/time.
* Use it to get the time for 1 day ago, 2 days ago, etc. `0` will give
* you the current time.
*/
def unixEpochTimeForNumberOfDaysAgo(numDaysAgo: Int): Long = {
import java.time._
val numDaysAgoDateTime: LocalDateTime = LocalDateTime.now().minusDays(numDaysAgo)
val zdt: ZonedDateTime = numDaysAgoDateTime.atZone(ZoneId.of("America/Denver"))
val numDaysAgoDateTimeInMillis = zdt.toInstant.toEpochMilli
val unixEpochTime = numDaysAgoDateTimeInMillis / 1000L
unixEpochTime
}
As shown in the comments, if you give it a 0
it will return the current epoch time. As shown by the function’s type signature, the function’s return type is a Long
(which is a 64-bit two's complement integer).
Of course you can make the code shorter and better; I just wanted to show the steps in the approach using the Date/Time classes that were introduced in Java 8.