QuickDzen
QuickDzen

Reputation: 277

C++ get UTC time with milliseconds

I need to get UTC time with milliseconds, I tried use it:

std::string getCurrentUTC()
{
    namespace bg = boost::gregorian;
    static char const* const fmt = "%Y-%b-%d %H:%M:%S";
    std::ostringstream ss;
    ss.imbue(std::locale(std::cout.getloc(), new bg::date_facet(fmt)));
    ss << bg::day_clock::universal_day();
    return ss.str();
}

But it prints the following:

2020-Jun-29 00:00:00

I need the following format:

2020-Jun-29 00:00:00.000

How can I solve this problem?

Upvotes: 1

Views: 2371

Answers (2)

Howard Hinnant
Howard Hinnant

Reputation: 218750

Using this free, open-source, header-only preview of C++20 <chrono> you can write:

#include "date/date.h"

#include <chrono>
#include <string>
#include <sstream>

std::string
getCurrentUTC()
{
    namespace ch = std::chrono;
    using date::operator<<;
    static char const* const fmt = "%Y-%b-%d %T";
    std::ostringstream ss;
    auto tp = ch::time_point_cast<ch::milliseconds>(ch::system_clock::now());
    ss << date::format(fmt, tp);
    return ss.str();
}

This works in C++11/14/17. For me it just output:

2020-Jun-29 13:42:21.946

which is the current time UTC to millisecond precision.

When C++20 <chrono> ships, this will port to it by:

  • Remove #include "date/date.h".
  • Remove using date::operator<<;
  • Add #include <format>
  • Change date::format to std::format
  • Change "%Y-%b-%d %T" to "{:%Y-%b-%d %T}".

Upvotes: 1

Farhad Sarvari
Farhad Sarvari

Reputation: 1081

You could get the UTC time with millisecond as follow:

struct timeb timebStruct;
ftime(&timebStruct);
struct tm               *tmStruct = new tm();
gmtime_r(&timebStruct.time, tmStruct);
std::cout <<  tmStruct->tm_hour
                            << tmStruct->tm_min <<  tmStruct->tm_sec <<  
timebStruct.millitm << std::endl

Upvotes: 2

Related Questions