Demo entry 1463095

mkgmtime

   

Submitted by anonymous on Mar 04, 2015 at 20:52
Language: C++. Code size: 901 Bytes.

// http://hhsprings.pinoko.jp/site-hhs/2015/03/mktime%E3%81%AEgmtutc%E7%89%88%E3%81%AF%E3%81%AA%E3%81%9C%E3%81%AA%E3%81%84%E3%81%AE%E3%81%8B/

#include <numeric>

//
// \displaystyle \lfloor{\frac{y}{4}\rfloor} \;-\; \lfloor{\frac{y}{100}\rfloor} \;+\; \lfloor{\frac{y}{400}\rfloor}
//
#define CNT_LEAP(y) ((int)((y) / 4) - (int)((y) / 100) + (int)((y) / 400))
time_t mkgmtime(
    short year, short mon, short day,
    short hour=0, short min=0, short sec=0)
{
    static const int dom[] = {
        31, 28, 31, 30, 31, 30,
        31, 31, 30, 31, 30, 31,
    };
    int days = 365 * (year - 1970) + CNT_LEAP(year - 1) - CNT_LEAP(1970 - 1);
    days += std::accumulate(&dom[0], &dom[mon - 1], 0);
    days += day - 1;
    if (mon > 2 && ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0)) {
        ++days;
    }
    return days * 86400 + hour * 3600 + min * 60 + sec;
}

This snippet took 0.01 seconds to highlight.

Back to the Entry List or Home.

Delete this entry (admin only).