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

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

I have to do everything myself (no time.h functions). Language - C.

+5
source share
5 answers

Disclaimer: The following code does not include leap years or leap seconds [Unix time does not include leap seconds. In any case, they are overrated. Ed.]. In addition, I have not tested it, so there may be errors. This can strike your cat and offend your mother. Have a nice day.

Try a little psuedocode (actually Python):

# 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 figured it out, please let me know. Doing this in C should not be too complicated.

+6
source

You really do not want to do this manually. You can write a simple code that assumes that years, months, days, hours, minutes and seconds are the same length (12 months, 28, 30 or 31 days, 24 hours, 60 minutes and 60 seconds) and come out with the wrong answer.

, , ( DST). ( UTC.)

glibc , strftime .


: UNIX .

+2
+1

You should have done a search - I sent the full answer to this question here only the other day (for UTC, at least for setting other time zones, just add or subtract the time zone offset in seconds from unixtime to the function call).

+1
source

You do not need to do math. It can be easily handled in C, like this,

char *ISO_Time (
    time_t                  time
)

{
    static char             mStr[128];
    struct tm              *gmt;

    gmt = gmtime (&time);

    strftime (mStr, sizeof(mStr), "%Y-%m-%dT%H:%M:%SZ", gmt);

    return mStr;
}

Since you do not have the exact ISO time, you just need to change one line,

strftime (mStr, sizeof(mStr), "%Y-%m-%d %H:%M:%S", gmt);
0
source

All Articles