qtutctimezone-offsetqdatetime

How to find out the UTC offset of my current location in Qt 5.1?


I had to write a function returning the offset from UTC of my current location. To my greatest surprize, the following code returned 0:

const QDateTime now = QDateTime::currentDateTime();
return now.toUTC().secsTo(now) / 60;

Solution

  • This is not as easy as it looks, because QDateTime::secsTo calculates offset after converting to UTC. I found an answer here, but I didn't really like the conversion to string and back. So my solution is:

    const QDateTime dateTime1 = QDateTime::currentDateTime();
    const QDateTime dateTime2 = QDateTime(dateTime1.date(), dateTime1.time(), Qt::UTC);
    return dateTime1.secsTo(dateTime2) / 60;