将UTC中的QDateTime转换为本地系统时间 [英] Convert a QDateTime in UTC to local system time

查看:2002
本文介绍了将UTC中的QDateTime转换为本地系统时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从这样的字符串构造一个QDateTime:

I construct a QDateTime from a string like this:

QDateTime date = QDateTime::fromString("2010-10-25T10:28:58.570Z", "yyyy-MM-ddTHH:mm:ss.zzzZ");

我知道 date 这是它的存储方式。但是当我想向用户显示此日期时,应该在用户的本地时区。 date.toLocalTime() 看起来很有前途,但是它返回完全相同的日期!

I know that date is in UTC because that is the way it's stored. But when I want to display this date to the user, it should be in the user's local time zone. date.toLocalTime() looks promising, but it returns the exact same date!

如何将 date 转换为系统的本地时间显示

How do I convert date to the system's local time to display to the user?

这里有一些失败:

#include <QtCore/QCoreApplication>
#include <QtCore/QDateTime>
#include <QtCore/QDebug>

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    QDateTime date = QDateTime::fromString("2010-10-25T10:28:58.570Z", "yyyy-MM-ddTHH:mm:ss.zzzZ");
    QDateTime local = date.toLocalTime();

    qDebug() << "utc: " << date;
    qDebug() << "local: " << local.toString();
    qDebug() << "hax: " << local.toString(Qt::SystemLocaleLongDate);

    return a.exec();
}

输出:

utc:  QDateTime("Mon Oct 25 10:28:58 2010")
local:  "Mon Oct 25 10:28:58 2010"
hax:  "Monday, October 25, 2010 10:28:58 AM"


推荐答案

QDateTime知道它是UTC还是本地时间。例如:

QDateTime knows whether it is UTC or local time. For example:

QDateTime utc = QDateTime::currentDateTimeUtc();
QDateTime local = QDateTime::currentDateTime();

local.secsTo(utc) // zero; these dates are the same even though I am in GMT-7

我们需要告诉 date 表示它是UTC日期时间, date.setTimeSpec(Qt :: UTC)

We need to tell date that it is a UTC date time with date.setTimeSpec(Qt::UTC):

#include <QtCore/QCoreApplication>
#include <QtCore/QDateTime>
#include <QtCore/QDebug>

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    QDateTime date = QDateTime::fromString("2010-10-25T10:28:58.570Z", "yyyy-MM-ddTHH:mm:ss.zzzZ");
    date.setTimeSpec(Qt::UTC);
    QDateTime local = date.toLocalTime();

    qDebug() << "utc: " << date;
    qDebug() << "local: " << local.toString();
    qDebug() << "hax: " << local.toString(Qt::SystemLocaleLongDate);

    return a.exec();
}

输出:

utc:  QDateTime("Mon Oct 25 10:28:58 2010") 
local:  "Mon Oct 25 03:28:58 2010" 
hax:  "Monday, October 25, 2010 3:28:58 AM"

我在GMT-7,所以这是对的。

I'm in GMT-7, so this is right.

这篇关于将UTC中的QDateTime转换为本地系统时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆