开发者

Qt: How to get the GMT offset of a device?

All is in the title! I develop on Qt开发者_如何学C 4.7.1 and it's for on a Nokia N8.

I think that I need to use: QDateTime and timeSpec (Qt::OffsetFromUTC).


Below is a function that returns the UTC/GMT offset for any timezone. For negative UTC offsets you must override this function and check the boolean "isNegative". I use this for sending requests to a server, if I want to check that its not the day the clock moves forwards or backwards I just call the function twice, once with today's date and then with tomorrow's date. If they both return the same then we know that the clock isn't switching in the next 24 hrs for Daylight Savings time.

QTime Calendar::getTimeZoneDiff(QDateTime midnightDateTime, bool &isNegative) {
    midnightDateTime.setTime(QTime(0,0));
    QDateTime utc   = midnightDateTime.toUTC();
    QDateTime local = midnightDateTime; 
    local.setTimeSpec(Qt::LocalTime);
    QDateTime offset = local.toUTC();
    QTime properTimeOffset = QTime(offset.time().hour(), offset.time().minute());
    offset.setTimeSpec(Qt::LocalTime);
    utc.setTimeSpec(Qt::UTC);

    if(offset.secsTo(utc) < 0){
        isNegative = true;
    }else{
        isNegative = false;
       properTimeOffset.setHMS(24 - properTimeOffset.hour() - (properTimeOffset.minute()/60.0) - (properTimeOffset.second()/3600.0), properTimeOffset.minute() - (properTimeOffset.second()/60.0), properTimeOffset.second());
        if(!properTimeOffset.isValid()){ //Midnight case
            properTimeOffset.setHMS(0,0,0);
        }
    }
   return properTimeOffset;
}

My solution is also posted here: Timezone offset


Yes and no. You're correct that Qt::OffsetFromUTC gives you the currently-in-use value.

But this will change given daylight saving time rules for the timezone you're in. It's a long-outstanding (not yet implemented) request to add full timezone support to QDateTime:

http://bugreports.qt-project.org/browse/QTBUG-71

I.e. right now, if you're using a device in France and ask for the UTC offset, you'll get one hour, but when switching to DST in March that'll change to two hours. Please keep that in mind.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜