Current Unix Timestamp SECONDS SINCE JAN 01 1970

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

How to convert Datetime to Unix timestamp in Kotlin

🎈 🎈 🎈
+1

    import java.time.LocalDateTime
    import java.time.ZoneOffset
    
    fun main() {
        val dateTime = LocalDateTime.of(2002, 1, 27, 7, 12, 13)
        val unixTimestamp = dateTime.toEpochSecond(ZoneOffset.UTC)
        println("Unix Timestamp: $unixTimestamp")
    }            
        

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

Code Explanation

To convert a date to Unix timestamp in Kotlin a LocalDateTime object is created for the specific date and time (2002-01-27 07:12:13). The toEpochSecond() method is then called on this LocalDateTime object, with ZoneOffset.UTC passed as the argument to ensure the conversion is based on UTC time.
The method calculates the number of seconds between the Unix epoch (January 1, 1970) and the specified date and time, effectively converting it to a Unix timestamp.


Other useful Kotlin date functions

Function Description Example
LocalDate.now() Returns the current date in the format 'YYYY-MM-DD'. LocalDate.now() returns 2024-08-28
LocalTime.now() Returns the current time in the format 'HH:mm:ss'. LocalTime.now() returns 12:34:56
LocalDateTime.now() Returns the current date and time in the format 'YYYY-MM-DDTHH:mm:ss'. LocalDateTime.now() returns 2024-08-28T12:34:56
Instant.now() Returns the current timestamp in UTC. Instant.now() returns 2024-08-28T12:34:56Z
Instant.ofEpochSecond() Converts a Unix timestamp (seconds since the Unix epoch) to an Instant. Instant.ofEpochSecond(1693227296L) returns 2024-08-28T12:34:56Z
LocalDate.parse() Parses a string to create a LocalDate object. LocalDate.parse("2024-08-28") returns 2024-08-28
LocalDateTime.parse() Parses a string to create a LocalDateTime object. LocalDateTime.parse("2024-08-28T12:34:56") returns 2024-08-28T12:34:56
ZonedDateTime.now() Returns the current date and time with the time zone information. ZonedDateTime.now() returns 2024-08-28T12:34:56+02:00[Europe/Paris]
DateTimeFormatter.ofPattern() Formats a date or time object according to a custom pattern. DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").format(LocalDateTime.now()) returns 2024-08-28 12:34:56
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