给定输入日期和时间(以字符串格式),我试图使用like中time
给出的函数获取它的纪元时间。将纪元时间转换回日期和时间会导致日期和时间比原始时间少一小时。我经历了一些讨论,说在夏令时的情况下可能会调整一小时。这是代码: ctime
mktime
time_t
//sample strptime program.
#include <iostream>
#include <ctime>
#include <string>
using namespace std;
long parseTime(string time) {
cout << "Time entered = " << time << endl;
long timeSinceEpoch;
struct tm t;
if(time.find("/") != string::npos) {
//format of date is mm/dd/yyyy. followed by clock in hh:mm (24 hour clock).
if(strptime(time.c_str(), "%m/%e/%Y %H:%M", &t) == NULL) {
cout << "Error. Check string for formatting." << endl;
}
} else if(time.find("-") != string::npos) {
//format of date is yyyy-mm-dd hh:mm:ss (hh in 24 hour clock format).
cout << "I am here." << endl;
if(strptime(time.c_str(), "%Y-%m-%e %H:%M:%S", &t) == NULL) {
cout << "Error. Check string for formatting of new date." << endl;
}
}
cout << "Details of the time structure:" << endl;
cout << "Years since 1900 = " << t.tm_year << endl;
cout << "Months since January = " << t.tm_mon << endl;
cout << "Day of the month = " << t.tm_mday << endl;
cout << "Hour = " << t.tm_hour << " Minute = " << t.tm_min << " second = " << t.tm_sec << endl;
timeSinceEpoch = mktime(&t);
time_t temp = mktime(&t);
cout << "Time since epoch = " << timeSinceEpoch << endl;
cout << "Reconverting to the time structure:" << endl;
struct tm* t2 = localtime(&temp);
cout << "Details of the time structure:" << endl;
cout << "Years since 1900 = " << t2->tm_year << endl;
cout << "Months since January = " << t2->tm_mon << endl;
cout << "Day of the month = " << t2->tm_mday << endl;
cout << "Hour = " << t2->tm_hour << " Minute = " << t2->tm_min << " second = " << t2->tm_sec << endl;
return timeSinceEpoch;
}
int main(int argc, char *argv[]) {
string date, t;
cout << "Enter date: " << endl;
cin >> date;
cout << "Enter time: " << endl;
cin >> t;
struct tm time;
string overall = date + " " + t;
long result = parseTime(overall);
cout << "Time in date + time = " << overall << " and since epoch = " << result << endl;
return 0;
}
麻烦的输入是:日期:2013-03-11 时间:04:41:53
我的问题:
1. 检查tm_idst
标志返回非零,表示 DST 有效。但是,我怎么知道正在谈论什么时区?
2. 上面给出的时间戳可能与我所在的时区不同。有没有办法指定时区以便tm_idst
正确设置标志?
3. 不确定时间戳记录在哪个时区时,如何处理夏令时?