Skip to content

Instantly share code, notes, and snippets.

@iamazeem
Last active October 30, 2024 07:53
Show Gist options
  • Select an option

  • Save iamazeem/a8b5299afd9c4bef9930f600833f0b4c to your computer and use it in GitHub Desktop.

Select an option

Save iamazeem/a8b5299afd9c4bef9930f600833f0b4c to your computer and use it in GitHub Desktop.
C++ timestamp with milliseconds (chrono + fmtlib)
// https://godbolt.org/z/7WW5vTsaY
#include <chrono>
#include <fmt/format.h>
#include <fmt/chrono.h>
int main()
{
const auto now = std::chrono::system_clock::now();
const auto now_sec = std::chrono::time_point_cast<std::chrono::seconds>(now);
const auto now_ms = std::chrono::time_point_cast<std::chrono::milliseconds>(now);
const auto ms = now_ms.time_since_epoch().count() % std::milli::den;
const auto ts = fmt::format("{:%FT%T}.{:03d}Z", now_sec, ms);
fmt::print("{}\n", ts);
}
// Sample output:
// 2024-10-30T07:50:08.553Z
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment