4

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;
mBardos
  • 2,872
  • 1
  • 19
  • 16

2 Answers2

6

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;
mBardos
  • 2,872
  • 1
  • 19
  • 16
0
int getTimezoneOffsetMinutes()
{
    const QDateTime now = QDateTime::currentDateTime();
    return now.timeZone().offsetFromUtc(now) / 60;
}
Sergey Galin
  • 426
  • 6
  • 8