【问题标题】:How to properly convert string to std::chrono::system_clock::time_point?如何正确地将字符串转换为 std::chrono::system_clock::time_point?
【发布时间】:2020-05-30 11:29:28
【问题描述】:

我已经对类似one 之类的问题进行了一些很好的回答。

然而,在将字符串转换为 time_point 并返回字符串后,我的代码似乎在一小时后给出了输出。

给出错误答案的代码:

#include <string>
#include <ctime>
#include <chrono>
#include <iomanip>
#include <iostream>
#include <sstream>

using date_time = std::chrono::system_clock::time_point;

std::string dateTimeToString(date_time time) {
    std::time_t now_c = std::chrono::system_clock::to_time_t(time);
    auto tm = std::localtime(&now_c);
    char buffer[32];
    std::strftime(buffer, 32, "%Y-%m-%d %H:%M:%S", tm);
    return std::string(buffer);
}

date_time stringToDateTime(const std::string &s) {
    std::tm timeDate = {};
    std::istringstream ss(s);
    ss >> std::get_time(&timeDate, "%Y-%m-%d %H:%M:%S");
    return std::chrono::system_clock::from_time_t(mktime(&timeDate));
}

int main() {
    std::string birthday = "2000-06-05 20:20:00";
    std::cout << "Two birthday dates: \n" << birthday << " \nsecond one:\n" << dateTimeToString(stringToDateTime(birthday))
              << "\n******************\n";
    return 0;
}

还有输出:

两个生日日期: 2000-06-05 20:20:00 第二个: 2000-06-05 21:20:00


我认为这与时区有关,但我无法解决这个问题。我的代码有什么问题?

【问题讨论】:

  • std::localtime 是(顾名思义),对您当地的时区敏感。
  • 对于 UTC:std::gmtime
  • 令人惊讶的是,std::gmtime 给出了“2000-06-05 19:20:00”的第二个生日输出。什么可能导致这种情况?

标签: c++ date-parsing datetime-parsing


【解决方案1】:

您可以使用boost 库进行时间管理。

看boost::date_time::parse_date(const std::string& s, int order_spec = ymd_order_iso):

//! Generic function to parse a delimited date (eg: 2002-02-10)
/*! Accepted formats are: "2003-02-10" or " 2003-Feb-10" or
 * "2003-Feburary-10"
 * The order in which the Month, Day, & Year appear in the argument
 * string can be accomodated by passing in the appropriate ymd_order_spec
 */

在boost::date_time::parse_delimited_time_duration(const std::string& s):

//! Creates a time_duration object from a delimited string
/*! Expected format for string is "[-]h[h][:mm][:ss][.fff]".
 * If the number of fractional digits provided is greater than the 
 * precision of the time duration type then the extra digits are 
 * truncated.
 *
 * A negative duration will be created if the first character in
 * string is a '-', all other '-' will be treated as delimiters.
 * Accepted delimiters are "-:,.". 
 */

Boost 对这两种方法都做了一个包装函数,可以解析日期时间字符串:

template<class time_type>
inline time_type parse_delimited_time(const std::string& s, char sep) {
    typedef typename time_type::time_duration_type time_duration;
    typedef typename time_type::date_type date_type;

    //split date/time on a unique delimiter char such as ' ' or 'T'
    std::string date_string, tod_string;
    split(s, sep, date_string, tod_string);
    //call parse_date with first string
    date_type d = parse_date<date_type>(date_string);
    //call parse_time_duration with remaining string
    time_duration td = parse_delimited_time_duration<time_duration>(tod_string);
    //construct a time
    return time_type(d, td);

}

如果你想要一个不同的日期格式解析器,我做了一个稍微不同的实现:

posix_time::ptime parse_dmy_time(const std::string &s, char sep) {
    typedef typename posix_time::ptime::time_duration_type time_duration;
    typedef typename posix_time::ptime::date_type date_type;

    //split date/time on a unique delimiter char such as ' ' or 'T'
    std::string date_string, tod_string;
    split(s, sep, date_string, tod_string);
    //call parse_date with first string
    auto d = parse_date<date_type>(date_string, ymd_order_dmy);
    //call parse_time_duration with remaining string
    auto td = parse_delimited_time_duration<time_duration>(tod_string);
    //construct a time
    return {d, td};
}

【讨论】:

  • 由于这是一个小组项目,如果没有必要,我宁愿不要添加更多外部库以避免复杂化。
  • @Spideyyyy boost 是非常推荐的库,相对于 STL 被称为并发症减少器,它的对象非常好用。我真的会考虑使用这个库,尤其是在大型项目中。这个库还附带了您将来可能需要的额外数据结构。您可以阅读提升优势:stackoverflow.com/questions/125580/…
【解决方案2】:

不确定它是否有帮助,但对我有用。在两个步骤中添加 UTC 偏移量和 TZ 信息(%z 和 %Z):

std::string dateTimeToString(date_time time) {
    std::time_t now_c = std::chrono::system_clock::to_time_t(time);
    auto tm = std::localtime(&now_c);
    char buffer[32];
    std::strftime(buffer, 32, "%Y-%m-%d %H:%M:%S%z %Z", tm);
    return std::string(buffer);
}

date_time stringToDateTime(const std::string& s) {
    std::tm timeDate = {};
    std::istringstream ss(s);
    ss >> std::get_time(&timeDate, "%Y-%m-%d %H:%M:%S%z %Z");
    return std::chrono::system_clock::from_time_t(mktime(&timeDate));
}

【讨论】:

  • @Spideyyyy "你住在 UTC 吗?" - 不,UTC offset 是特定地点与协调世界时 (UTC) 的小时和分钟差和日期。我只是注意到get_time 不解析%z 和%Z,所以我需要稍后再仔细看看。
猜你喜欢
  • 2018-07-27
  • 2016-04-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-12-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多