Current Unix Timestamp SECONDS SINCE JAN 01 1970

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

How to convert Datetime to Unix timestamp in Haskell

🎈 🎈 🎈
+1

    import Data.Time.Clock.POSIX (utcTimeToPOSIXSeconds)
    import Data.Time.Calendar (fromGregorian)
    import Data.Time (UTCTime(..), secondsToDiffTime)
    
    -- Convert DateTime to Unix timestamp (2020 date)
    dateTime :: UTCTime
    dateTime = UTCTime (fromGregorian 2020 5 15) (secondsToDiffTime $ 8 * 3600 + 30 * 60 + 45)
    
    unixTimestamp :: Integer
    unixTimestamp = round (utcTimeToPOSIXSeconds dateTime)
    
    main :: IO ()
    main = putStrLn $ "Unix Timestamp: " ++ show unixTimestamp            
        

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

Code Explanation

In this Haskell example, we create a UTCTime object for the date '2020-05-15 08:30:45' UTC using the UTCTime constructor. The utcTimeToPOSIXSeconds function is used to convert the UTCTime object to a Unix timestamp.
When run, this code will output: Unix Timestamp: 1652603445


Other useful Haskell date functions

Function Description Example
getCurrentTime Returns the current UTC time as a UTCTime object. getCurrentTime returns 2024-08-28 12:34:56 UTC
posixSecondsToUTCTime Converts a Unix timestamp (POSIX time) to a UTCTime object. posixSecondsToUTCTime 1652602245 returns 2022-05-15 08:10:45 UTC
utcTimeToPOSIXSeconds Converts a UTCTime object to a Unix timestamp (POSIX time) in seconds. utcTimeToPOSIXSeconds dateTime returns 1652602245
fromGregorian Creates a Day (date) from a Gregorian year, month, and day. fromGregorian 2022 5 15 returns 2022-05-15
UTCTime Constructs a UTC time from a Day and a DiffTime. UTCTime (fromGregorian 2022 5 15) (secondsToDiffTime 30645) creates 2022-05-15 08:10:45 UTC
formatTime Formats a UTCTime or Day as a string using a specified format. formatTime defaultTimeLocale "%Y-%m-%d %H:%M:%S" dateTime returns 2022-05-15 08:10:45
addUTCTime Adds a number of seconds to a UTCTime object. addUTCTime 3600 dateTime adds 1 hour to the date.
diffUTCTime Calculates the difference in seconds between two UTCTime objects. diffUTCTime time1 time2 returns the difference in seconds between two times.
secondsToDiffTime Converts a number of seconds to a DiffTime object (used for times in UTCTime). secondsToDiffTime 30645 returns 8 hours, 30 minutes, and 45 seconds.
getZonedTime Returns the current local time and time zone as a ZonedTime object. getZonedTime returns the current local time with time zone information.
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