using namespace std::chrono;
tm timeInAmerica = {0};
timeInAmerica.tm_year = 75;//1975
timeInAmerica.tm_mon = 0;//January
timeInAmerica.tm_mday = 31;
timeInAmerica.tm_hour = 23;
timeInAmerica.tm_min = 23;
timeInAmerica.tm_sec = 23;
auto lt = local_days{year{timeInAmerica.tm_year+1900}
/month(timeInAmerica.tm_mon+1)
/timeInAmerica.tm_mday}
+ hours{timeInAmerica.tm_hour}
+ minutes{timeInAmerica.tm_min}
+ seconds{timeInAmerica.tm_sec};
auto timeZone = locate_zone("America/New_York");
auto sysTime = timeZone->to_sys(lt);
auto sysDay = floor<days>(sysTime);
year_month_day ymd = sysDay;
hh_mm_ss hms{sysTime - sysDay};
int y = int{ymd.year()};
int m = unsigned{ymd.month()};
int d = unsigned{ymd.day()};
int h = hms.hours().count();
int M = hms.minutes().count();
int s = hms.seconds().count();
我发布了using namespace std::chrono 只是为了将冗长的内容降低到低吼声。如果您希望将std::chrono:: 放在所有正确的位置,也可以。
lt 是代表当地时间所需的local_time<seconds>(或只是local_seconds)。从tm 转换时,请注意偏差(1900 和 1)。
要将sysTime 转换回{year, month, day, hour, minute, second} 结构,首先将sysTime 截断为天精度time_point。那么,days-precision time_point 可以转换为 {year, month, day} 数据结构。
一天中的时间只是 date_time 减去日期。这可以转换为{hours, minutes, seconds} 数据结构:hh_mm_ss。
year_month_day 和 hh_mm_ss 都有获取强类型字段的 getter。然后每个强类型字段都转换为整数,如上所示。转换回 tm 时,不要忘记偏差(1900 和 1)。
此外,所有东西都有一个流操作符。这使得调试非常方便:
cout << "lt = " << lt << '\n'; // 1975-01-31 23:23:23
cout << "sysTime = " << sysTime << '\n'; // 1975-02-01 04:23:23
cout << "sysDay = " << sysDay << '\n'; // 1975-02-01
cout << "ymd = " << ymd << '\n'; // 1975-02-01
cout << "hms = " << hms << '\n'; // 04:23:23