Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;
like image 454
mBardos Avatar asked Oct 19 '25 06:10

mBardos


2 Answers

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;
like image 195
mBardos Avatar answered Oct 22 '25 05:10

mBardos


int getTimezoneOffsetMinutes()
{
    const QDateTime now = QDateTime::currentDateTime();
    return now.timeZone().offsetFromUtc(now) / 60;
}
like image 37
Sergey Galin Avatar answered Oct 22 '25 04:10

Sergey Galin