Convert a QDateTime in UTC to local system time

前端 未结 2 1569
粉色の甜心
粉色の甜心 2021-02-13 11:40

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\");
2条回答
  •  长发绾君心
    2021-02-13 12:31

    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
    

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

    #include 
    #include 
    #include 
    
    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();
    }
    

    Output:

    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"
    

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

提交回复
热议问题