The Admiral
The Admiral

Reputation: 31

Converting epoch to UTC date format using date.h

A very simple question. I have been using date.h to get epoch in milliseconds and nanoseconds from a full datestamp.

     istringstream temp_ss1{timestamp1};
     sys_time<nanoseconds> tp1;
     temp_ss1 >> parse("%Y/%m/%d,%T", tp1);
     std::cout << tp1.time_since_epoch().count() << "ns\n";

What is the method to go from a millisecond epoch to a full datestamp with milliseconds?

Thank you very much for your help !

Upvotes: 2

Views: 307

Answers (1)

Howard Hinnant
Howard Hinnant

Reputation: 218750

If you're not picky about the format, you can stream the sys_time<milliseconds> out. If you would like to control the format, you can use date::format with these formatting flags. For example:

std::cout << format("%Y/%m/%d,%T", tp1) << '\n';

The precision of the output will match the precision of the time_point.

Is there a method to convert. "long epoch = 1609330278454" is there a function which take a long and prints a date?

#include "date/date.h"
#include <iostream>

int
main()
{
    using namespace date;
    using namespace std;
    using namespace std::chrono;

    long epoch = 1609330278454;
    cout << sys_time<milliseconds>{milliseconds{epoch}} << '\n';
}

Outputs:

2020-12-30 12:11:18.454

You can customize the format like so:

long epoch = 1609330278454;
sys_time<milliseconds> tp{milliseconds{epoch}};
cout << format("%Y/%m/%d,%T", tp) << '\n';

Output:

2020/12/30,12:11:18.454

Upvotes: 1

Related Questions