【问题标题】:Convert tm of another timezone into tm of the GMT timezone将另一个时区的 tm 转换为 GMT 时区的 tm
【发布时间】:2022-01-24 12:47:27
【问题描述】:

我正在使用 chrono 和 c++20。

我有一个 EST 时区的 tm 结构,但不知道如何获取 GMT 时区的相应时间。

这是我一直在想的:

tm timeInAmerica = {0};
timeInAmerica.tm_year = 75;//1975
timeInAmerica.tm_month = 0;//January
timeInAmerica.tm_mday = 31;
timeInAmerica.tm_hour = 23;
timeInAmerica.tm_minute = 23;
timeInAmerica.tm_second = 23;

auto timeZone = std::chrono::locate_zone("America/New_York");
auto sysTime = timeZone->to_sys( /*needs local_time */ );

...我不知道如何将 tm 转换为 local_time 以便将其输入 to_sys()

我也不知道如何将返回的 sysTime 值转换回 tm(这将允许我检查 GMT 年、月、日、小时、分钟)。

【问题讨论】:

  • "这将允许我检查 GMT 年、月、日" 您可以通过将时间转换为 chrono::year_month_day 来检查这些。
  • @NicolBolas 谢谢,我也想保持小时,分钟。我将编辑我的问题

标签: c++ timezone c++20 chrono


【解决方案1】:
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&lt;seconds&gt;(或只是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_dayhh_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

【讨论】:

    猜你喜欢
    • 2016-05-23
    • 2019-04-14
    • 1970-01-01
    • 2012-10-27
    • 1970-01-01
    • 1970-01-01
    • 2021-08-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多