Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to convert a date format with a time zone to time_t format? #767

Open
vvpnet opened this issue Dec 23, 2022 · 1 comment
Open

How to convert a date format with a time zone to time_t format? #767

vvpnet opened this issue Dec 23, 2022 · 1 comment

Comments

@vvpnet
Copy link

vvpnet commented Dec 23, 2022

Hi!
There is a string format: "2018-12-15 04:49:00+07"
How do I get the time_t format?
How do I get utc time?

What if the format is like this: "2018-12-15 04:49:00.000+07"
How can I get msec separately?
Thanks!

@HowardHinnant
Copy link
Owner

Here's the first part:

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

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

    string s = "2018-12-15 04:49:00+07";
    istringstream in{std::move(s)};
    in.exceptions(ios::failbit);
    sys_seconds tp;
    in >> parse("%F %T%z", tp);
    cout << format("%F %T %z", tp) << '\n';       // 2018-12-14 21:49:00 +0000
    cout << system_clock::to_time_t(tp) << '\n';  // 1544824140
}

sys_seconds is a type alias for time_point<system_clock, seconds>. And system_clock is defined to be Unix Time (UTC excluding leap seconds). The parse knows that tp represents UTC by its type, and therefore subtracts the UTC offset from the local time for you.

To handle milliseconds you simply change type of tp:

    sys_time<milliseconds> tp;

You could have also used the milliseconds-precision tp on the first string.

To get the milliseconds field separately, just truncate tp to seconds and subtract that off:

    auto ms = tp - floor<seconds>(tp);

ms has type milliseconds.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants