Sunday, December 29, 2013

Three ways to get UTC time in C++

1. C++ way:
#include <ctime>

std
::string currentDateTimeUTC( )
{
    struct tm tm;
    std::time_t time = std::time(nullptr);

    if (gmtime_s(&tm, &time))
        return ("");

    char utc[_countof("1970-01-01T00:00:00")];
    strftime(utc_countof(utc), "%Y-%m-%dT%H:%M:%S", &tm);

    return (utc);
}

auto result = currentDateTimeUTC( );

2. boost way:
#include <boost/date_time/posix_time/posix_time.hpp>

using namespace boost::posix_time;
auto result = to_iso_extended_string(second_clock::universal_time());

3. Qt way:
#include <QDateTime>
auto result = QDateTime::currentDateTimeUtc().toString(Qt::ISODate).toStdString();