CTime tm类计算日期间隔
搜索查询日期间隔的方法的时候,找到tm类。这个类可以实现简单的日期计算,比如设置好年月日就能从tm_wday知道是星期几。
struct tm {
int tm_sec; /* seconds after the minute - [0,59] */
int tm_min; /* minutes after the hour - [0,59] */
int tm_hour; /* hours since midnight - [0,23] */
int tm_mday; /* day of the month - [1,31] */
int tm_mon; /* months since January - [0,11] 当前月减去1*/
int tm_year; /* years since 1900 * 当前年减去1900/
int tm_wday; /* days since Sunday - [0,6] */
int tm_yday; /* days since January 1 - [0,365] */
int tm_isdst; /* daylight savings time flag */
};
#include <cstdio> #include <ctime> #include <iostream> #include <cstring> #include <conio.h> using std::memset; using std::tm; using std::mktime; using std::cout; using std::endl; int main() { struct tm Time1,Time2; //需要全部重置 memset(&Time1, 0, sizeof(tm)); memset(&Time2, 0, sizeof(tm)); time_t Res1,Res2; //时间范围有限制,似乎是[70-138],即1970-2138 Time1.tm_year = 138; Time1.tm_mon = 6; Time1.tm_mday = 1; Time1.tm_hour = 1; Time1.tm_min = 2; Time1.tm_sec = 3; Time2.tm_year = 110; Time2.tm_mon = 6; Time2.tm_mday = 1; Time2.tm_hour = 1; Time2.tm_min = 2; Time2.tm_sec = 3; Res1 = mktime(&Time1); Res2 = mktime(&Time2); printf("%ld %ld\n", Res1, Res2); int DayNum = (Res1 - Res2)/(24*60*60); cout << DayNum << endl; //也可以这样设置【秒,分,小时,天,月,年】 struct tm t1 = { 0, 0, 0, 4, 7, 80 }; // Warning! month between [0, 11] struct tm t2 = { 0, 0, 0, 7, 8, 104 }; // Year from 1900 int days = (mktime(&t2) - mktime(&t1)) / (24*60*60); cout << days << endl; }
/* mktime example: weekday calculator */ #include <stdio.h> /* printf, scanf */ #include <time.h> /* time_t, struct tm, time, mktime */ int main () { time_t rawtime; struct tm * timeinfo; int year, month ,day; const char * weekday[] = { "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"}; /* prompt user for date */ printf ("Enter year: "); scanf ("%d",&year); printf ("Enter month: "); scanf ("%d",&month); printf ("Enter day: "); scanf ("%d",&day); /* get current timeinfo and modify it to the user's choice */ time ( &rawtime ); timeinfo = localtime ( &rawtime ); timeinfo->tm_year = year - 1900; timeinfo->tm_mon = month - 1; timeinfo->tm_mday = day; /* call mktime: timeinfo->tm_wday will be set */ mktime ( timeinfo ); printf ("That day is a %s.\n", weekday[timeinfo->tm_wday]); return 0; }