Current Unix Timestamp SECONDS SINCE JAN 01 1970

Current UTC Time
2025-08-20
Convert Datetime to Unix Timestamp in Groovy

How to convert Datetime to Unix timestamp in Groovy

🎈 🎈 🎈
+1

    // Convert Date to Unix timestamp
    Date date = new Date(122, 4, 15, 0, 56, 57) // 2022-05-15 00:56:57
    long unixTimestamp = date.getTime() / 1000
    
    println "Unix Timestamp: ${unixTimestamp}"
        

Output:
Unix Timestamp: 1652576217
Example only. There may be multiple ways to perform this operation.

Code Explanation

In this example of date to Unix timestamp conversion using Groovy, a Date object is created representing '2022-05-15 08:10:45'. In Groovy (and Java), the Date constructor uses a zero-based year and month, therefore, 122 represents the year 2022 (since it's the number of years since 1900) and 4 represents the month May (since it's zero-based, 0 = January, so 4 = May).
The getTime() method is called on the Date object, which returns the number of milliseconds since the Unix epoch.
Dividing this value by 1000 converts it to a Unix timestamp in seconds. The result is the Unix timestamp '1652576217', which is printed.


Other useful Groovy date functions

Function Description Example
new Date() Returns the current date and time as a Date object. new Date() returns 2024-08-28 12:34:56
new Date(long millis) Creates a Date object for the specified number of milliseconds since the Unix epoch. new Date(1652602245000L) returns 2022-05-15 08:10:45
getTime() Returns the number of milliseconds since the Unix epoch for a Date object. date.getTime() returns 1652602245000L
Date.parse() Parses a string representation of a date into a Date object using a specific format. Date.parse("yyyy-MM-dd", "2024-08-28") returns 2024-08-28
format() Formats a Date object as a string using a specified format. date.format("yyyy-MM-dd HH:mm:ss") returns 2022-05-15 08:10:45
clearTime() Clears the time portion of a Date object, leaving only the date. date.clearTime() sets the time to 00:00:00.
plus() Adds a number of days to a Date object. date.plus(5) adds 5 days to the date.
minus() Subtracts a number of days from a Date object. date.minus(3) subtracts 3 days from the date.
use(TimeCategory) Adds or subtracts time units such as hours, minutes, and seconds in a human-readable way. use(TimeCategory) { date + 5.hours } adds 5 hours to the date.
Calendar.getInstance() Returns a Calendar object representing the current date and time. Calendar.getInstance() returns the current date and time as a Calendar object.
Current Unix Timestamp SECONDS SINCE JAN 01 1970

Current UTC Time
2025-08-20
Ad Banner Placeholder
Ad Banner Placeholder
Ad Banner Placeholder
Ad Banner Placeholder