The Linux Page

Using QDateTime to output a date string and UTC

As I'm working on a server I need dates in UTC. By default, the QDateTime object generates dates in local time.

How do you change that? There is a toUTC() but my input data is already UTC so using toUTC() would mess up the date and I'd get the same result anyway.

The idea is actually pretty simple. The toUTC() creates a QDateTime object in UTC mode. This is done like this:

QDateTime utc(QDateTime().toUTC());

Now the utc object is in UTC mode and can be used with your Unix dates as in:

utc.setTime_t(time(NULL));

and the string output can be generated with toString() as in:

date.toString("ddd, dd MMM yyyy hh:mm:ss' GMT'");

to generate a standard date used by HTTP.

By setting up the utc object before calling the setTime_t() function we get the correct result.