问题描述
如何转换2012-03-02"?into unix epoch time in C? 确实提供了解决方案.但它使用 tm_yday 而不是 tm 结构的 tm_mday 和 tm_mon.
The 2nd answer in How do I convert "2012-03-02" into unix epoch time in C? does provides the solution. But it uses tm_yday instead of tm_mday and tm_mon of tm structure.
我的输入是人类可读的日期和时间,期望的输出是 UNIX 纪元时间.
My Input is human readable date and time and the desired output is UNIX epoch time.
int main(int argc, char *argv[])
{
char timeString[80] = {"05 07 2021 00 33 51"}; //epoch is 1620347631000
struct tm my_tm = {0};
if(sscanf(timeString, "%d %d %d %d %d %d", &my_tm.tm_mon, &my_tm.tm_mday, &my_tm.tm_year, &my_tm.tm_hour, &my_tm.tm_min, &my_tm.tm_sec)!=6)
{
/* ... error parsing ... */
printf(" sscanf failed");
}
// In the below formula, I can't use my_tm.tm_yday as I don't have the value for it.
//I want to use my_tm.tm_mday and tm_mon.
printf("%d",my_tm.tm_sec + my_tm.tm_min*60 + my_tm.tm_hour*3600 + my_tm.tm_yday*86400 +
(my_tm.tm_year-70)*31536000 + ((my_tm.tm_year-69)/4)*86400 -
((my_tm.tm_year-1)/100)*86400 + ((my_tm.tm_year+299)/400)*86400 );
return EXIT_SUCCESS;
}
所以,换句话说,我正在寻找 my_tm.tm_yday*86400 的替代品 my_tm.tm_mday 和 my_tm.tm_mon
So, in other words, I'm looking for a replacement for my_tm.tm_yday*86400 in terms of my_tm.tm_mday and my_tm.tm_mon
推荐答案
公历采用日期"范围内的一年到 INT_MAX
并且可以将 1 到 12 范围内的月份转换为从零开始的年日";通过以下辅助函数在 0 到 365 范围内:
A year in the range "date of adoption of Gregorian calendar" to INT_MAX
and a month in the range 1 to 12 can be converted to a zero-based "year day" in the range 0 to 365 by the following helper function:
int yday(int year, int month)
{
static const short int upto[12] =
{0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334};
int yd;
yd = upto[month - 1];
if (month > 2 && isleap(year))
yd++;
return yd;
}
使用以下辅助函数 isyear
,该函数在采用公历的日期"范围内花费一年时间;到 INT_MAX
并且如果年份不是闰年则返回 0,如果年份是闰年则返回 1:
That uses the following helper function isyear
that takes a year in the range "date of adoption of Gregorian calendar" to INT_MAX
and returns 0 if the year is not a leap year, 1 if the year is a leap year:
int isleap(int year)
{
return year % 4 == 0 && (year % 100 != 0 || year % 400 == 0);
}
这篇关于如何计算给定 tm_mday 和 tm_mon 的 tm_yday?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!