Qt使用时区将时间和日期字符串转换为QDateTime

时间:2016-04-21 05:03:47

标签: c++ qt date datetime

我尝试使用以下格式转换日期字符串:

Thu Sep 18 02:03:02 +0000 2008

到QDateTime,使用

QDateTime::FromString()

如果我删除+0000时区并使用输入格式:

ddd MMM dd hh:mm:ss yyyy

但是,它似乎没有时区支持,我无法找到一种方法来忽略使用通配符的时区部分。

有没有办法使用时区或只是忽略+0000部分?

1 个答案:

答案 0 :(得分:1)

This is a little extreme, but you could use another date/time lib (this one for example) just for the purpose of reformatting the string to what QDateTime wants.

#include "tz.h"
#include <chrono>
#include <iostream>
#include <sstream>

int
main()
{
    using namespace date;
    std::string input = "Thu Sep 18 02:03:02 +0000 2008";
    std::istringstream stream{input};
    sys_seconds tp;
    parse(stream, "%a %b %d %T %z %Y", tp);
    std::string output = format("%a %b %d %T %Y", tp);
    std::cout << output << '\n';
}

which outputs:

Thu Sep 18 02:03:02 2008

With this library the time point will be correctly converted to UTC (using the UTC offset) during the conversion.