I have an iso date return from REST api:
2018-05-07T06:46:24.763Z
And I want to convert it to local datetime, let say in Philippines, it's +8. So should be
2018-05-07T14:46:24.763Z
And I want to extract the time only:
14:46
And convert it to std::string.
How can I do it?
Do I need to specify the local timezone or is there an automatic getting timezone just like how javascript work in browser?
Thank you.
If you would like to use Howard Hinnant's free, open-source date/time library, here is what it could look like:
#include "date/tz.h"
#include <iostream>
#include <sstream>
#include <string>
std::string
time_in_philippines(const std::string& utc)
{
using namespace std;
using namespace std::chrono;
using namespace date;
istringstream in{utc};
sys_time<milliseconds> tp;
in >> parse("%FT%TZ", tp);
auto zt = make_zoned("Asia/Manila", tp);
return format("%H:%M", zt);
}
int
main()
{
std::cout << time_in_philippines("2018-05-07T06:46:24.763Z") << '\n';
}
This program outputs:
14:46
sys_time<milliseconds> is just a chrono::time_point based on chrono::system_clock, but with milliseconds precision. The parse function will parse the time_point out of the istream using the indicated parsing flags.
The time_point is implicitly UTC. To convert it to a zoned_time<milliseconds> one pairs the UTC time_point with a time_zone ("Asia/Manila" in this example). If your computer's current local time zone is already "Asia/Manila", one could also pick up the current time zone with:
auto zt = make_zoned(current_zone(), tp);
Next one just formats the zoned_time with the desired flags, "%H:%M" in this case. format returns a std::string.
Some installation is required for working with the time zone library.
Related
Coming from C# I'm a bit lost with the datetime functionality in C++. I am simply looking to convert from a string in the format 2023-01-12T07:00:00+08:00 to the number of seconds since 1-1-2023 UTC.
And the reverse, i.e. an int of the number of seconds since the start of 2023 to a string in the format "%Y-%m-%dT%H:%M:%S%z". Any code or pointers in the right direction would be greatly appreciated.
Have tried various options using chrono and time_t which seems to work:
std::time_t getTime(const std::string& dateTime) {
std::chrono::sys_time<std::chrono::seconds> tTime;
std::istringstream stream(dateTime);
std::chrono::from_stream(stream, "%Y-%m-%dT%H:%M:%S%z", tTime);
return std::chrono::system_clock::to_time_t(tTime);
}
const time_t EPOCH_2023 = getTime("2023-01-01T00:00:00+00:00");
int stringToIntTime(const std::string& dateTime) {
return static_cast<int>(getTime(dateTime) - EPOCH_2023);
}
to get the int.
But I haven't a clue on doing the reverse.
Here is what I recommend:
#include <chrono>
#include <format>
#include <iostream>
#include <sstream>
using namespace std::chrono_literals;
constexpr std::chrono::sys_seconds EPOCH_2023 = std::chrono::sys_days{2023y/01/01};
int
stringToIntTime(const std::string& dateTime)
{
using namespace std;
using namespace std::chrono;
sys_seconds tTime;
istringstream stream(dateTime);
stream >> parse("%FT%T%Ez", tTime);
return (tTime - EPOCH_2023)/1s;
}
std::string
intToStringTime(int i)
{
using namespace std;
using namespace std::chrono;
sys_seconds t = EPOCH_2023 + seconds{i};
return format("{:%FT%T%Ez}", zoned_time{"Etc/GMT-8", t});
}
int
main()
{
using namespace std;
int i = stringToIntTime("2023-01-12T07:00:00+08:00");
string s = intToStringTime(i);
cout << i << '\n';
cout << s << '\n';
}
Which should output:
946800
2023-01-12T07:00:00+08:00
I've taken the liberty of simplifying your stringToIntTime somewhat:
Your EPOCH_2023 constant can be made more efficient by storing it in a sys_seconds type as opposed to a string, and making it constexpr. In the object code this will just be a integral literal which is the count of seconds between your epoch and the system_clock epoch of 1970-01-01.
stringToIntTime is correct, but I've simplified it down to one function and used parse in place of from_stream just for slightly cleaner syntax. parse is a slightly higher level API.
Also note the use of %Ez in place of %z. The former includes the : separator between the hours and minutes of the UTC offset.
There's no need to go through the C API with time_t. One can just subtract the parsed UTC time tTime from your epoch. This results in seconds since your epoch. To convert that to int, just divide by 1 second.
intToStringTime starts with converting the int to seconds and adding that to your epoch. This gives t the type sys_seconds and the value of a time_point with seconds since the system_clock epoch.
Finally just format t, using a time zone with the +08:00 UTC offset, using the desired format. Note the use of -8 in the name to give +8 for the offset. This is simply POSIX weirdness that IANA inherits. If some other time zone is desired, just sub that in for "Etc/GMT-8".
Note the use of %T which is a shortcut for %H:%M:%S and %F which is a shortcut for %Y-%m-%d.
The best way is probably to use sscanf_s (stdio.h since C11) or strptime (POSIX standard) to convert the string into either individual values or a tm type (time.h), respectively. From there you can use mktime (time.h) to get back a time_t type. Then just subtract them. How to convert a string variable containing time to time_t type in c++?
I'm writing a method to parse date/time strings in a variety of formats.
std::chrono::system_clock::time_point toTimePoint(const std::string str) {
... a bunch of code that determines the format of the input string
std::string formatStr = string{"%Y-%m-%d"}
+ " " // Delimeter between date and time.
+ "%H:%M:%S"
+ "%t%Z"
;
// The %t should be 0 or 1 whitespace
// The %Z should be a timezone name
std::chrono::system_clock::time_point retVal;
std::istringstream in{str};
in >> date::parse(formatStr, retVal);
return retVal;
}
I then test it with a variety of inputs. The other formats work. I can do these:
2022-04-01 12:17:00.1234
2022-04-01 12:17:00.1234-0600
2022-04-01 12:17:00.1234-06:00
The latter two are for US Mountain Daylight Time. It does all the right things. The first one shows as 12:17:00 UST. The other two are 18:17:00 UST. Working great. I've omitted all that code for brevity. What does not work is this:
2022-04-01 12:17:00.1234 US/Central
I've tried a variety of timezone names after writing a different program to dump the ones known by Howard's library. None of them matter. I get a UST-time value with no time zone offset.
Luckily, what I need right now is the -06:00 format, so I can move forward. But I'd like to fix the code, as we have other places that use timezone names, and I'd like to get this working properly.
I'm not sure what I'm doing wrong.
When reading an offset with %z (e.g. -0600), combined with a sys_time type such as system_clock::time_point, the parse time point is interpreted as a local time, and the offset is applied to get the sys_time, as desired in your first two examples.
However this is not the case when reading a time zone name or abbreviation with %Z (note the change from lower case z to upper case Z).
%Z parses a time zone abbreviation or name, which is just a string. The common case is for this to just parse an abbreviation, e.g. CST. And in general, there is no unique mapping from an abbreviation to an offset. And so the offset can not be internally applied. Thus the parsed value should always be interpreted as a local time.
However all is not lost. You can parse the time zone name with %Z into a string, and then look up the time_zone with that name and use it to convert the parse local_time into a sys_time. This could look like:
#include "date/tz.h"
#include <chrono>
#include <iostream>
#include <sstream>
int
main()
{
using namespace date;
using namespace std;
using namespace std::chrono;
istringstream in{"2022-04-01 12:17:00.1234 US/Central"};
string tz_name;
local_time<microseconds> local_tp;
in >> parse("%F %T%t%Z", local_tp, tz_name);
system_clock::time_point tp = locate_zone(tz_name)->to_sys(local_tp);
cout << tp << '\n';
}
Just add a string as the third argument in your parse call, and make sure the first argument is a local_time instead of a sys_time. Then use locate_zone to get a time_zone const* and call to_sys with that, passing in the parsed local_time.
The above program outputs:
2022-04-01 17:17:00.123400
This is an hour off from the -6h offset because US/Central goes to daylight saving on 2022-03-13 (-5h offset).
A program like this
int
main()
{
using namespace date;
std::cout << std::chrono::system_clock::now() << '\n';
}
prints something like 2017-09-15 13:11:34.356648.
Assume I have a string literal "2017-09-15 13:11:34.356648" in my code.
What is the right way to create std::chrono::time_point from it in C++20?
Just to be clear, there is no namespace date in C++20. So the code in the question should look like:
#include <chrono>
#include <iostream>
int
main()
{
std::cout << std::chrono::system_clock::now() << '\n';
}
The inverse of this is std::chrono::parse which operates on streams. You can also use std::chrono::from_stream if desired. parse is a stream manipulator that makes the syntax a little nicer.
istringstream in{"2017-09-15 13:11:34.356648"};
system_clock::time_point tp;
in >> parse("%F %T", tp);
(I've dropped the namespaces just to keep the verbosity down)
The locale used is the global locale in effect at the time the istringstream is constructed. If you prefer another locale use the imbue member function to set the desired locale. The locale will only impact the decimal point character in this example.
The %T will read up to whatever precision the input time_point has (which varies with platform from microseconds to nanoseconds). If you want to be sure you can parse nanoseconds even if system_clock::time_point is coarser than that, then you can parse into a sys_time<nanoseconds> which is a type alias for time_point<system_clock, nanoseconds>.
sys_time<nanoseconds> tp;
in >> parse("%F %T", tp);
If the input stream has precision less than the input time_point, there is no problem. What the stream has will be read, and no more. If the input stream has precision finer than the input time_point, then the parse stops at the precision of the time_point, and the remaining digits are left unparsed in the stream.
Other strptime-like parsing flags are supported.
I have a lot of strings that are in the form "HH:MM" and I constantly have to do arithmetic on them (for example add 5 minutes, add 24 hours, etc).
I am wondering if there is any built in class in the standard library that can handle such arithmetic instead of having to manually change the string and handle corner cases?
If you don't have strptime available, and if you have <chrono> and don't want to fool around with the C API, you can use Howard Hinnant's free, open-source, portable datetime library to write helpers to convert to and from std::chrono::minutes.
So convert from string to minutes, do whatever computation you need, and then convert back to string:
#include "date.h"
#include <iostream>
#include <string>
#include <sstream>
std::chrono::minutes
to_minutes(const std::string& s)
{
std::istringstream in{s};
in.exceptions(std::ios::failbit);
std::chrono::minutes m;
in >> date::parse("%H:%M", m);
return m;
}
std::string
to_string(std::chrono::minutes m)
{
return date::format("%H:%M", m);
}
int
main()
{
using namespace std::chrono_literals;
std::cout << to_string(to_minutes("5:47") + 2h + 168min) << '\n';
}
Output:
10:35
This library has been ported to recent versions of VS, gcc and clang.
You can also use this library to work with different precisions quite seamlessly, for example seconds, or even milliseconds, and even mix all the precisions you need together:
std::chrono::milliseconds
to_milliseconds(const std::string& s)
{
std::istringstream in{s};
in.exceptions(std::ios::failbit);
std::chrono::milliseconds ms;
in >> date::parse("%T", ms);
return ms;
}
std::string
to_string(std::chrono::milliseconds ms)
{
return date::format("%T", ms);
}
// ...
std::cout << to_string(to_minutes("5:47") + 2h + 168min +
122s + 465ms + to_milliseconds("1:23:02.123")) << '\n';
Output:
12:00:04.588
Using <ctime> you can convert your HH:MM string to a struct tm as follows:
struct tm time_components;
memset(&time_components, 0, sizeof(struct tm));
time_components.tm_year = 2017;
strptime("01:45", "%H:%M", &time_components);
This assumes you have strptime available. If not, use sscanf or something similar to extract your hour and minute components--I'm sure you're doing this already. I'm setting tm_year there because otherwise it's zero, which is not a valid year for the conversion to time_t later on.
We can easily convert the tm struct back into a HH:MM string using strftime.
char buf[6];
strftime(buf, 6, "%H:%M", &time_components);
printf("time_components before manipulation: %s\n", buf);
But how about manipulating it? My first thought was 'just convert to time_t and add/subtract however many seconds you want'. But time_t isn't guaranteed to be in seconds, so don't do that. Instead, add whatever number of minutes you like to the tm_min component of the tm struct, then call mktime with it, which will correctly handle any values that are outside the normal bounds of hours/minutes/seconds. At that point you have a time_t, which we don't want to mess with, so just convert that back into a tm using localtime. localtime will mirror the conversion that occurred in mktime, so you shouldn't have to worry about time zones and so on. Now you've essentially normalized the tm structure, and your overflowing minutes have been converted to hours, and your overflowing hours have been converted to days.
time_components.tm_min += 65; // Add 65 minutes. Negative values work as expected too!
time_t temp_time = mktime(&time_components);
struct tm* adjusted_time = localtime(&temp_time);
strftime(buf, 6, "%H:%M", adjusted_time);
printf("adjusted_time: %s\n", buf);
That adjusted_time pointer seems to point to an internal tm struct that will change in any subsequent calls to mktime or gmtime, FYI.
There's no doubt this is a fairly hellish approach. If all you need to do is handle minute/hour overflow and simple arithmetic, I'd be tempted to roll my own or look elsewhere.
http://en.cppreference.com/w/cpp/chrono/duration supports the arithmetic and types you want, but I don't think you can construct from strings.
However you can with Boost Chrono. I tend to prefer it for most cases, because if I'm dealing with the problem of hours and minutes, I'll probably end up dealing with dates too in the future.
I am trying to use std::chrono to make a std::string but running into issues.
Here is the C(-ish) code I want to mimick:
std::uint32_t time_date_stamp = 1484693089;
char date[100];
struct tm *t = gmtime(reinterpret_cast<const time_t*>(&time_date_stamp));
strftime(date, sizeof(date), "%Y-%m-%d %I:%M:%S %p", t);
My starting point is always this std::uint32_t, it is from a data format I do not control.
Sorry I do not have any C++ as a starting point, I do not even know how to make a std::chrono::time_point correctly.
Here's an easy way to do it without dropping down to C's tm using this portable C++11/14 free, open-source, header-only library.
#include "date.h"
#include <iostream>
#include <string>
int
main()
{
std::uint32_t time_date_stamp = 1484693089;
date::sys_seconds tp{std::chrono::seconds{time_date_stamp}};
std::string s = date::format("%Y-%m-%d %I:%M:%S %p", tp);
std::cout << s << '\n';
}
This outputs:
2017-01-17 10:44:49 PM
This does not have the thread-safety issues associated with the ancient gmtime C function.
date::sys_seconds above is a typedef for std::chrono::time_point<std::chrono::system_clock, std::chrono::seconds>.
<chrono> is not a library for formatting datetimes into strings. It is useful for converting different time representations (milliseconds to days, etc), adding timestamps together and such.
The only datetime formatting functions in the standard library are the ones inherited from the C standard library, including the std::strftime which you already used in the "C(-ish)" version. EDIT: As pointed out by jaggedSpire, C++11 introduced std::put_time. It provides a convenient way to stream formatted dates with the same API as used by the C functions.
Since std::gmtime (and std::localtime if you were to use that) take their argument as a unix timestamp, you don't need <chrono> to convert the time. It is already in the correct representation. Only the underlying type must be converted from std::uint32_t to std::time_t. That is not implemented portably in your C version.
A portable way to convert the timestamp, with std::put_time based formatting:
std::uint32_t time_date_stamp = 1484693089;
std::time_t temp = time_date_stamp;
std::tm* t = std::gmtime(&temp);
std::stringstream ss; // or if you're going to print, just input directly into the output stream
ss << std::put_time(t, "%Y-%m-%d %I:%M:%S %p");
std::string output = ss.str();