您可以使用days_from_civil,即described here in detail
// Returns number of days since civil 1970-01-01. Negative values indicate
// days prior to 1970-01-01.
// Preconditions: y-m-d represents a date in the civil (Gregorian) calendar
// m is in [1, 12]
// d is in [1, last_day_of_month(y, m)]
// y is "approximately" in
// [numeric_limits<Int>::min()/366, numeric_limits<Int>::max()/366]
// Exact range of validity is:
// [civil_from_days(numeric_limits<Int>::min()),
// civil_from_days(numeric_limits<Int>::max()-719468)]
template <class Int>
constexpr
Int
days_from_civil(Int y, unsigned m, unsigned d) noexcept
{
static_assert(std::numeric_limits<unsigned>::digits >= 18,
"This algorithm has not been ported to a 16 bit unsigned integer");
static_assert(std::numeric_limits<Int>::digits >= 20,
"This algorithm has not been ported to a 16 bit signed integer");
y -= m <= 2;
const Int era = (y >= 0 ? y : y-399) / 400;
const unsigned yoe = static_cast<unsigned>(y - era * 400); // [0, 399]
const unsigned doy = (153*(m + (m > 2 ? -3 : 9)) + 2)/5 + d-1; // [0, 365]
const unsigned doe = yoe * 365 + yoe/4 - yoe/100 + doy; // [0, 146096]
return era * 146097 + static_cast<Int>(doe) - 719468;
}
将tm 中的 {year,month,day} 三元组转换为自纪元 (1970-01-01) 以来的天数。从tm 转换这些字段时要小心,因为它们的怪癖(例如tm_year + 1900)。
将此天数乘以 86400,然后加上来自 tm 的 {hours, minutes, seconds} 数据(每个都转换为秒)。
你就完成了。不要担心闰秒,timegm 也不担心它们。如果您真的关心闰秒,我有一个C++11/14 solution available to deal with that,但我猜这比您想了解的要多。
不要被上面显示的 C++14 语法吓到。将此算法转换为 C(或任何其他语言)是微不足道的。