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.
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++?
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 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();
This question already has answers here:
Getting the current time as a YYYY-MM-DD-HH-MM-SS string
(2 answers)
Closed 8 years ago.
I have a function which returns a timestamp in unix time as int.
I need to convert this int to a string dd/mm/yy in local time. The "local" part is causing me problems, if it weren't for that, I could have just made my own function to convert it.
I have searched around , and it seems the ctime class from the standard library would be ideal for this, in a manner like this:
int unixtime;
std::cout << std::asctime(std::localtime(unixtime));
Sadly, only *time_t is accepted. Is there any way I can convert int into this format, or any better way to get local time from unix time as int?
time_t is by definition an arithmetic type, you can just do:
time_t ts = unixtime;
std::cout << std::asctime(std::localtime(&ts));
'/* localtime example */
#include <stdio.h> /* puts, printf */
#include <time.h> /* time_t, struct tm, time, localtime */
int main ()
{
time_t rawtime;
struct tm * timeinfo;
time (&rawtime);
timeinfo = localtime (&rawtime);
printf ("Current local time and date: %s", asctime(timeinfo));
return 0;
}'
You can simply use type time_t it will give you the time.
"The ctime(), gmtime() and localtime() functions all take an argument of data type time_t which represents calendar time. When interpreted as an absolute time value, it represents the number of seconds elapsed since the Epoch, 1970-01-01 00:00:00 +0000 (UTC)."
sources:
http://linux.die.net/man/3/ctime
http://linux.die.net/man/7/time
To print current time in dd/mm/yy, you may try the following:
#include <iostream>
#include <ctime>
int main(int argc, const char** argv)
{
char date_buff[40];
time_t time_value = time(0);
struct tm* my_tm = localtime(&time_value);
strftime(date_buff, sizeof(date_buff), "%d/%m/%y\n", my_tm);
std::cout << date_buff << std::endl;
return 0;
}
The type of time_t is not guaranteed by the C specification.
Unix and POSIX-compliant systems implement the time_t type as a signed integer (typically 32 or 64 bits wide) which represents the number of seconds since the start of the Unix epoch. So you may just do the following
std::time_t my_time = static_cast<std::time_t>(unixtime);
However, it is better to not to assume time to be an int and replace your time function with the appropriate time handling and return std::time_t or struct tm
I want to convert a time_t to a string and back again.
I'd like to convert the time to a string using ctime().
I can't seem to find anything on google or the time.h header file, any ideas?
Basically what I'm trying to do is store a date in a file, and then read it back so I can use it as a time_t again.
Also, no library references outside of std,mfc.
One more note, this will have to function on Windows xp and above and that's it.
Edit
All I want to do is convert a time_t into a string(I don't care if it's human readable) and then convert it back to a time_t. I'm basically just trying to store the time_t into a file and read it again(but I don't want any code for that, as there will be more info in the file besides a time_t).
You'll have to write your own function to do that. These functions convert any primitive type (or any type which overloads operator<< and/or operator>>) to a string, and viceversa:
template<typename T>
std::string StringUtils::toString(const T &t) {
std::ostringstream oss;
oss << t;
return oss.str();
}
template<typename T>
T StringUtils::fromString( const std::string& s ) {
std::istringstream stream( s );
T t;
stream >> t;
return t;
}
ctime() returns a pointer to a character buffer that uses a specific formatting. You could use sprintf() to parse such a string into its individual portions, store them in a struct tm, and use mktime() to convert that to a time_t.
The time_t Wikipedia article article sheds some light on this. The bottom line is that the type of time_t is not guaranteed in the C specification. Here is an example of what you can try:
Try stringstream.
#include <string>
#include <sstream>
time_t seconds;
time(&seconds);
std::stringstream ss;
ss << seconds;
std::string ts = ss.str();
A nice wrapper around the above technique is Boost's lexical_cast:
#include <boost/lexical_cast.hpp>
#include <string>
time_t t;
time(&t);
std::string ts = boost::lexical_cast<std::string>(seconds);
Wikipedia on time_t:
The time_t datatype is a data type in
the ISO C library defined for storing
system time values. Such values are
returned from the standard time()
library function. This type is a
typedef defined in the standard
header. ISO C defines
time_t as an arithmetic type, but does
not specify any particular type,
range, resolution, or encoding for it.
Also unspecified are the meanings of
arithmetic operations applied to time
values.
Unix and POSIX-compliant systems implement the time_t type as a signed
integer (typically 32 or 64 bits wide)
which represents the number of seconds
since the start of the Unix epoch:
midnight UTC of January 1, 1970 (not
counting leap seconds). Some systems
correctly handle negative time values,
while others do not. Systems using a
32-bit time_t type are susceptible to
the Year 2038 problem.
Convert the time_t to struct tm using gmtime(), then convert the struct tm to plain text (preferably ISO 8601 format) using strftime(). The result will be portable, human readable, and machine readable.
To get back to the time_t, you just parse the string back into a struct tm and use mktime().