【问题标题】:C++: Converting date-time between timezones keeping precisionC ++:在时区之间转换日期时间以保持精度
【发布时间】:2014-04-13 14:40:47
【问题描述】:

考虑输入:2014-04-14T16:28:07.023(无时区,毫秒精度) 我解析了它,我将这些部分作为数字。

  • 输入始终被视为采用 UTC 格式
  • 我想显示为当地时间
  • 我想在显示时保持毫秒精度

我有 C++98 和 boost 1.51。

我检查了high_resolution_clocksystem_clock,但还无法为问题生成最终图。

【问题讨论】:

  • 接受的答案here 回答你的问题了吗?
  • 那里没有毫秒。我也没有看到 utc-localtime 转换。但仍然可能导致某个地方......
  • 经典c++是什么意思?您的意思是 1999 年的 C++99 标准年与 2011 年的经典 C++11 并列。在过去 20 年的 C++ 中,与您的问题相关的任何内容都没有变化。所以你不使用提升。我将从学习如何处理文本开始。您可能可以打开 boost 代码并看看他们做了什么。即使你不打算使用它。
  • 我知道如何处理文本,我不应该提到解析。让我们从我将零件作为数字的那一点开始。我在为其余部分选择实用程序和方法的良好组合时遇到问题。
  • C++ 有一个 1998 年的 C++98 标准,以及一个名为 C++03 的 2003 年更新,用于修复标准文本中的一些错误,而不添加功能。 (从 1999 年开始,C 确实有 C99 标准。)

标签: c++ boost time


【解决方案1】:

根据 cmets 的要求作为答案发布,以下是不使用 Boost 的方法:

#include <iostream>
#include <stdlib.h>
#include <time.h>

int main() {
  int year, month, day, hour, minute, second, millisecond;
  if (std::cin >> year >> month >> day >> hour >> minute >> second >> millisecond) {
    struct tm utc;
    utc.tm_year = year;
    utc.tm_mon = month;
    utc.tm_mday = day;
    utc.tm_hour = hour;
    utc.tm_min = minute;
    utc.tm_sec = second;
    utc.tm_isdst = 0;

    time_t time = timegm(&utc);
    if (time == (time_t) -1)
      abort();

    struct tm *local = localtime(&time);
    if (localtime == NULL)
      abort();

    year = local->tm_year;
    month = local->tm_mon;
    day = local->tm_mday;
    hour = local->tm_hour;
    minute = local->tm_min;
    second = local->tm_sec;

    std::cout << year << ' ' << month << ' ' << day << ' ' << hour << ' ' << minute << ' ' << second << ' ' << millisecond << std::endl;
  }
}

请注意,millisecond 变量是从输入读取并写入输出,无需任何修改。

这使用了非标准的 timegm 函数,但该函数的文档包含一个更便携的实现,如果需要,您可以包含它。

【讨论】:

    【解决方案2】:

    我有一个对我来说足够的解决方案,但我不知道这是否是总体上最好的方法。我即将使用boost::posix_time::ptimeboost::date_timec_local_adjustor

    #include <iostream>
    #include <boost/date_time.hpp>
    #include <boost/date_time/c_local_time_adjustor.hpp>
    
    int main()
    {
      typedef boost::posix_time::ptime TP;
      typedef boost::date_time::c_local_adjustor<TP> local_adj;
    
      TP tUTC(boost::gregorian::date(2014,4,13),boost::posix_time::millisec(23));
      TP tLocal(local_adj::utc_to_local(tUTC));
    
      std::cout << boost::posix_time::to_simple_string(tUTC) << std::endl;
      std::cout << boost::posix_time::to_simple_string(tLocal) << std::endl;
    
      return 0;
    }
    

    将打印:

    2014-Apr-13 00:00:00.023000
    2014-Apr-13 02:00:00.023000
    

    我没有使用using namespace 来显示在哪里是什么。 ptime 类可以访问我需要的每个细节。 c_local_adjustor 没有 local_to_utc 方法,但可以解决。

    chrono 无处可去,我只能在文档中做圆圈。)

    【讨论】:

    • +1 这是我在系统宕机时想写的。 Chrono 是“无用的”,因为它(故意)与日历无关。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-03
    • 1970-01-01
    相关资源
    最近更新 更多