Press "Enter" to skip to content

Unix Timestamp in Qt using QDateTime class

Francesco Mondello 0

Sometimes we may need to use unix timestamp in our Qt applications.

From Wikipedia:

Unix time (a.k.a. POSIX time or Epoch time) is a system for describing instants in time, defined as the number of seconds that have elapsed since 00:00:00 Coordinated Universal Time (UTC), Thursday, 1 January 1970, not counting leap seconds. It is used widely in Unix-like and many other operating systems and file formats. Due to its handling of leap seconds, it is neither a linear representation of time nor a true representation of UTC. Unix time may be checked on most Unix systems by typing date +%s on the command line.

The QDateTime class of Qt Framework provides useful methods useful for manipulating date and time functions.

Here are some explicative examples on how to get the current time in unix timestamp format.

Example 1. Getting the system time in unix timestamp format:

/* This retrieves the  current date and time as reported by the system clock, in the local time zone. */

QDateTime currentDateTime = QDateTime::QDate::currentDate();

/* Returns the datetime as the number of seconds that have passed since 1970-01-01T00:00:00, Coordinated Universal Time  */

uint unixtime = currentDateTime.toTime_t();

Example 2: Getting the current date and time in UTC in unix timestamp format:

/* This retrieves the  current date and time, as reported by the system clock, in UTC. */

QDateTime currentDateTime = QDateTime::QDate::currentDateUtc();

/* Returns the datetime as the number of seconds that have passed since 1970-01-01T00:00:00, Coordinated Universal Time  */

uint unixtime = currentDateTime.toTime_t();

Example 3: Setting the QDateTime variable using unix timestamp value:

/* Wednesday, February 4, 2015 4:00 pm to Unix time */

uint unixtimestamp = 1423062000;

QDateTime myDateTime;

myDateTime.setTime_t(unixtimestamp);

You can find more here: QDateTime Documentation.

Comments are closed.