Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting unix timestamp to YYYY-MM-DD HH:MM:SS

I have a Unix timestamp that I need to get the individual year, month, day, hour, minute and second values from. I never was very good in math class so I was wondering if you guys could help me out a little :)

I have to do everything myself (no time.h functions). The language is C.

like image 222
Baggins Avatar asked Aug 14 '09 20:08

Baggins


2 Answers

Disclaimer: The following code does not account for leap years or leap seconds [Unix time does not account for leap seconds. They're overrated, anyway. -Ed]. Also, I did not test it, so there may be bugs. It may kick your cat and insult your mother. Have a nice day.

Let's try a little psuedocode (Python, really):

# Define some constants here...

# You'll have to figure these out.  Don't forget about February (leap years)...
secondsPerMonth = [ SECONDS_IN_JANUARY, SECONDS_IN_FEBRUARY, ... ]

def formatTime(secondsSinceEpoch):
    # / is integer division in this case.
    # Account for leap years when you get around to it :)
    year = 1970 + secondsSinceEpoch / SECONDS_IN_YEAR
    acc = secondsSinceEpoch - year * SECONDS_IN_YEAR

    for month in range(12):
        if secondsPerMonth[month] < acc:
            acc -= month
            month += 1

    month += 1

    # Again, / is integer division.
    days = acc / SECONDS_PER_DAY
    acc -= days * SECONDS_PER_DAY

    hours = acc / SECONDS_PER_HOUR
    acc -= hours * SECONDS_PER_HOUR

    minutes = acc / SECONDS_PER_MINUTE
    acc -= minutes * SECONDS_PER_MINUTE

    seconds = acc

    return "%d-%d-%d %d:%d%d" % (year, month, day, hours, minutes, seconds)

If I goofed up, please let me know. Doing this in C shouldn't be too much harder.

like image 78
Andrew Keeton Avatar answered Oct 05 '22 22:10

Andrew Keeton


You really do not want to do this by hand. You could write up some simple code that assumes years, months, days, hours, minutes and seconds are all the same lengths (12 months; 28, 30, or 31 days; 24 hours; 60 minutes; and 60 seconds) and come up with the wrong answer.

To get the right answer, you have to handle leap years and leap seconds, and convert to the local time zone (with the right DST mode). (Unless you choose to only display in UTC time.)

I suggest that you have a look at the code of glibc and see how strftime works.


Edit: UNIX time does not use the leap second.

like image 42
Kevin Panko Avatar answered Oct 06 '22 00:10

Kevin Panko