怎么根据当前系统时间对数据成员如year进行初始化而不只是输出字符串?
思路:时区做了一个简单的转换,目前用系统当前时间(time系统调用获取的秒数)加上指定时区偏移,然后通过gmtime转换为UTC时间(即GMT+0时间)。前提条件是要求的时区数量有限,而且与GMT时间偏差已知。
如果要实现一个适用于各个时区的对象,会很麻烦,可能最少需要一天时间。不过有人已经写了现成的,如果需要可以参考一下github muduo项目。思路是读取/usr/share/zoneinfo/
下面的时区文件,将其转换为local time。
以下代码适用于Unix/Linux系统,设计Time class,满足要求的6点。
#include <iostream>
#include <sys/time.h>
using namespace std;
enum class TimeZoneOffset : int
{
Greenwich = 0,
Beijing = 8,
NewYork = -5,
Tokyo = 9,
Paris = 2,
};
class Time
{
public:
explicit Time(TimeZoneOffset zone = TimeZoneOffset::Greenwich)
{
time_t now_time;
tm* tmptr;
time(&now_time); // 获取当前系统时间
now_time += static_cast<int>(zone) * 3600;
tmptr = gmtime(&now_time); // 转换为UTC时间
if (!tmptr) {
perror("gmtime error");
exit(-1);
}
else {
year = tmptr->tm_year + 1900;
month = tmptr->tm_mon + 1;
day = tmptr->tm_mday;
hour = tmptr->tm_hour;
minute = tmptr->tm_min;
second = tmptr->tm_sec;
}
}
int get_year() const {
return year;
}
int get_month() const {
return month;
}
int get_day() const {
return day;
}
int get_hour() const {
return hour;
}
int get_minute() const {
return minute;
}
int get_second() const {
return second;
}
void print() {
printf("%4d-%02d-%02d %02d:%02d:%02d\n",
year, month, day,
hour, minute, second);
}
private:
int hour;
int minute;
int second;
int year;
int month;
int day;
};
int main()
{
Time t0;
t0.print();
Time t1(TimeZoneOffset::Beijing);
t1.print();
Time t2(TimeZoneOffset::NewYork);
t2.print();
Time t3(TimeZoneOffset::Tokyo);
t3.print();
Time t4(TimeZoneOffset::Paris);
t4.print();
return 0;
}
测试结果:
2022-05-22 15:56:04
2022-05-22 23:56:04
2022-05-22 10:56:04
2022-05-23 00:56:04
2022-05-22 17:56:04
拿去
#include <iostream>
using namespace std;
class Time
{
public:
Time();
Time(int h, int m ,int s);
Time operator +(Time &t1);
Time operator >>(Time &t1);
Time operator <<(Time &t1);
void setHour(int h )
{
hour=h;
}
void setMinute(int m)
{
minute=m;
}
void setSecond(int s)
{
second=s;
}
int getHour()
{
return hour;
}
int getMinute()
{
return minute;
}
int getSecond()
{
return second;
}
private:
int hour;
int minute;
int second;
};
Time::Time()
{
hour=0;
minute=0;
second=0;
}
Time::Time(int h, int m ,int s)
{
hour=h;
minute=m;
second=s;
}
Time Time::operator +(Time &t1)
{
return Time(hour+t1.getHour(),minute+t1.getMinute(),second+t1.getSecond());
}
Time Time::operator >>(Time &t1)
{
int a,b,c;
cout<<"inputTime1:"<<endl;
cin>>a>>b>>c;
hour=a;
minute=b;
second=c;
cout<<"inputTime2:"<<endl;
cin>>a>>b>>c;
t1.setHour(a);
t1.setMinute(b);
t1.setSecond(c);
return Time(hour+t1.getHour(),minute+t1.getMinute(),second+t1.getSecond());
}
Time Time::operator <<(Time &t1)
{
cout<<t1.getHour()<<':'<<t1.getMinute()<<':'<<t1.getSecond()<<endl;
return Time(hour+t1.getHour(),minute+t1.getMinute(),second+t1.getSecond());
}
int main()
{
Time time1(1,2,3);
Time time2(2,3,4);
Time time3;
time3 = time1+time2;
time3 = time1>>time2;
time3<<(time1+time2);
}