c++的获取绝对秒函数的使用
利用绝对秒函数,可实现各种时间的加减运算,代码如下
unsigned long stime(int year, int mon,int day, int hour, int min, int sec) { if (0 >= (int) (mon -= 2)) { /* 1..12 -> 11,12,1..10 */ mon += 12; /* Puts Feb last since it has leap day */ year -= 1; } return ((( (unsigned long)(year/4 - year/100 + year/400 + 367*mon/12 + day) + year*365 - 719499 )*24 + hour /* now have hours */ )*60 + min /* now have minutes */ )*60 + sec; /* finally seconds */ }
下面是利用这个函数所写的类:
//class.h const char* WEEK[7+1] = {"","星期一","星期二","星期三","星期四","星期五","星期六","星期日"}; class Time { private: int day; int month; int year; int week; public: Time(int d = 0, int m = 0, int y = 0):day(d),month(m),year(y){} //返回当前天的星期 const char* getthisday(){return WEEK[week];} long operator - (Time& t); //friend friend std::istream& operator >> (std::istream& is, Time& t); //输入 friend std::ostream& operator << (std::ostream& os, const Time& t); //输出 }; std::istream& operator >> (std::istream& is, Time& t) { is >> t.year >> t.month >> t.day; //转载星期算法 t.week = ( t.day + 2*t.month + 3*(t.month+1)/5 + t.year + t.year/4 - t.year/100 + t.year/400) % 7+1; return is; } std::ostream& operator << (std::ostream& os, const Time& t) { os << t.year << "-" << t.month << "-" << t.day << "-" << WEEK[t.week]; return os; } long Time::operator - (Time& t) { unsigned long a = stime(year, month, day, 0, 0, 0); unsigned long b = stime(t.year, t.month, t.day, 0, 0, 0); return (a>b)?(a-b)/(3600*24):(b-a)/(3600*24); }
main函数:
#include <iostream> #include "class.h" using std::cin; using std::cout; using std::endl; int main() { Time a,b; cout << "输入第一个日期(年/月/日): "; cin >> a; cout << "输入第二个日期(年/月/日): "; cin >> b; //实现星期的计算 cout << a << endl; cout << b << endl; //实现天数差计算 cout << "两个日期间隔: " << a-b << "天" << endl; cin.get(); cin.get(); return 0; }
Trackback from your site.