我使用sscanf将相关变量拉出来:
sscanf(tIDe_str1.c_str(),"%d %d %d %d %Lf",&y1,&j1,&h1,&m1,&obs1);sscanf(tIDe_str2.c_str(),&y2,&j2,&h2,&m2,&obs2);
对于此特定数据集,值为2011 083 23 22 1.1
然后我创建并填充一个tm结构,运行mktime,在两天之间的cout调用,它从083变为364.
int y1=2011,j1=83,h1=23,m1=22;struct tm time_struct = {0,0},*time_ptr = &time_struct;time_t tv_min;time_struct.tm_year = y1 - 1900;time_struct.tm_yday = j1;cout << time_struct.tm_yday << endl;time_struct.tm_hour = h1;time_struct.tm_min = m1;time_struct.tm_isdst = -1;cout << time_struct.tm_yday << endl;tv_min = mktime(time_ptr);cout << time_struct.tm_yday << endl;
这是为什么?是因为tm_mday和tm_mon设置为0?我最初尝试不将它全部初始化为零,但随后mktime返回-1.如果我只知道年份而不是月份和月份,我应该做些什么呢?
解决方法 mktime()正在做它应该做的事情.引用C标准:
The mktime function converts the broken-down time,expressed as
local time,in the structure pointed to by timeptr into a calendar
time value with the same enCoding as that of the values returned by
the time function. The original values of the tm_wday and
tm_yday components of the structure are ignored,and the original values of the other components are not restricted to the ranges
indicated above. On successful completion,the values of the
tm_wday and tm_yday components of the structure are set appropriately,and the other components are set to represent the
specifIEd calendar time,but with their values forced to the ranges
indicated above; the final value of tm_mdayis not set until tm_mon
and tm_year are determined.
mktime()可以从其他成员计算tm_mday和tm_yday的值;它不是为了计算这些字段中其他成员的值而设计的.
但是,您可以做的是使用超出范围的值初始化struct tm.例如,如果您希望tm_yday为200(一年中的第200天),则可以初始化表示1月200日的结构tm.然后mktime()会将其标准化为正确的日期,产生一个time_t值,然后您可以将其提供给gmtime()或localtime().
这是一个简单的例子:
#include <iostream>#include <ctime>int main(){ struct tm t = { 0 }; t.tm_sec = t.tm_min = t.tm_hour = 0; // mIDnight t.tm_mon = 0; // January t.tm_year = 2012 - 1900; t.tm_isdst = -1; // unkNown t.tm_mday = 200; // January 200th? time_t when = mktime(&t); const struct tm *norm = localtime(&when); // normalized time std::cout << "month=" << norm->tm_mon << ",day=" << norm->tm_mday << "\n"; std::cout << "The 200th day of 2012 starts " << asctime(norm);}
输出是:
month=6,day=18The 200th day of 2012 starts Wed Jul 18 00:00:00 2012总结
以上是内存溢出为你收集整理的c – 为什么mktime()改变了我的tm结构的年份?全部内容,希望文章能够帮你解决c – 为什么mktime()改变了我的tm结构的年份?所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)