一、原理
C++Qt 向baidu发送请求,获取互联网时间,然后转本地时间
二、遇到的问题
在Qt中将获取到的时间日期转QDateTime时,转化失败,不知道什么原因,只能自己手写一个字符串拆分
QDateTime dt = QDateTime::fromString("Thu, 18 May 2023 05:38:45 GMT", "ddd, dd MMM yyyy hh:mm:ss 'GMT'");
不知道为什么转化失败???有人知道吗
之前自己手写一个字符串拆分,现在找到了解决方法,感谢@mideum
已解决
代码
#include <QtNetwork/QNetworkAccessManager> #include <QtNetwork/QNetworkReply> #include <QDateTime> #include <QDebug> #include <QTimeZone> #include <QDate> #include <QTime> void QtNetDate::getNetDateTime() { QNetworkAccessManager *manager = new QNetworkAccessManager(); QNetworkReply *reply = manager->get(QNetworkRequest(QUrl("http://www.baidu.com"))); QObject::connect(reply, &QNetworkReply::finished, [=]() { if (reply->error() != QNetworkReply::NoError) { qDebug() << "Error:" << reply->errorString(); return; } QString dateStr = reply->rawHeader("Date"); QDateTime m_dt = getDateTime(dateStr); qDebug() << m_dt.toString("yyyy-MM-dd hh:mm:ss"); reply->deleteLater(); manager->deleteLater(); }); } //字符串拆分 QDateTime QtNetDate::getDateTime(QString str_datetime) { //"Thu, 18 May 2023 05:38:45 GMT" int year = str_datetime.mid(12, 4).toInt(); QString str_month = str_datetime.mid(8, 3); QVector<QString> months = { "Jan","Feb","Mar","Apr" ,"May" ,"Jun" ,"Jul" ,"Aug" ,"Sep" ,"Oct" ,"Nov" ,"Dec" }; int month; if (months.contains(str_month)) month = months.indexOf(str_month) + 1; int day = str_datetime.mid(5, 2).toInt(); int hour = str_datetime.mid(17, 2).toInt(); int minute = str_datetime.mid(20, 2).toInt(); int second = str_datetime.mid(23, 2).toInt(); QDateTime dt(QDate(year, month, day), QTime(hour, minute, second), Qt::UTC); QTimeZone localZone = QTimeZone::systemTimeZone(); dt = dt.toTimeZone(localZone); return dt; }
推荐一个零声学院项目课,个人觉得老师讲得不错,分享给大家: