将 UTC 格式的 QDateTime 转换为本地系统时间
我从这样的字符串构造一个 QDateTime:
QDateTime date = QDateTime::fromString("2010-10-25T10:28:58.570Z", "yyyy-MM-ddTHH:mm:ss.zzzZ");
我知道 date
采用 UTC 格式,因为这就是它的存储方式。但是当我想向用户显示这个日期时,它应该是用户的本地时区。 date.toLocalTime()
看起来很有希望,但它返回确切的值同一日期!
如何将日期
转换为系统本地时间以显示给用户?
以下是更多失败:
#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"
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");
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!
How do I convert date
to the system's local time to display to the user?
Here are some more failures:
#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();
}
Output:
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"
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
QDateTime 知道它是 UTC 还是本地时间。例如:
我们需要告诉
date
这是一个 UTC 日期时间,使用date.setTimeSpec(Qt::UTC)
:输出:
I'm in GMT-7,所以这是对的。
QDateTime knows whether it is UTC or local time. For example:
We need to tell
date
that it is a UTC date time withdate.setTimeSpec(Qt::UTC)
:Output:
I'm in GMT-7, so this is right.
使用 QDateTime::toString() 是否没有给您预期的结果?
也许您可以尝试使用
QDateTime::toString(Qt::SystemLocaleLongDate)
或QDateTime::toString(Qt::SystemLocaleShortDate)
使用不同的格式。否则,我会尝试使用 QLocale::dateTimeFormat() 获取本地格式为
QString
,然后使用该字符串作为 的格式参数QDateTime::toString(),但我认为它不会改变任何东西。Is using QDateTime::toString() not giving you expected results ?
Maybe you could try using a different format with
QDateTime::toString(Qt::SystemLocaleLongDate)
orQDateTime::toString(Qt::SystemLocaleShortDate)
.Otherwise, I would try to use QLocale::dateTimeFormat() to get the local format as a
QString
and then use this string as the format parameter of QDateTime::toString(), but I don't think it will change anything.