Hello I have the following date that I am consuming from an api
string sToParse = "2020-04-17T09:30:00-04:00";
which should be in human form "Friday, April 17, 2020 08:30:00" central time
or epoch of 1587130200
however this code
cout << "raw: " << sToParse << endl;
static const std::string dateTimeFormat { "%Y-%m-%dT%H:%M:%S%Z" };
istringstream ss{ sToParse };
tm dt;
ss >> get_time(&dt, dateTimeFormat.c_str());
cout << mktime(&dt) << endl;
Gives me an epoch of 1587137400 which is a human format of "Friday, April 17, 2020 10:30:00 AM" which is two hours difference. How do i get the %Z to process the timezone appropriately?
Thanks in advance for any help you can give
C++20 will do this:
#include <chrono>
#include <iostream>
#include <sstream>
#include <string>
int
main()
{
using namespace std;
using namespace std::chrono;
string sToParse = "2020-04-17T09:30:00-04:00";
cout << "raw: " << sToParse << endl;
static const std::string dateTimeFormat { "%Y-%m-%dT%H:%M:%S%z" };
istringstream ss{ sToParse };
sys_seconds dt;
ss >> parse(dateTimeFormat, dt);
cout << dt << '\n';
cout << dt.time_since_epoch() << '\n';
}
Output:
2020-04-17 13:30:00
1587130200s
This gets the "epoch time" you're looking for. The big difference is the use of %z instead of %Z. %z is the command for parsing the offset. %Z parses time zone abbreviation.
This doesn't get the "human time" you're expecting. The time printed out above is UTC. This is clearly correct on inspection: 13:30:00 is 4 hours after 09:30:00.
If you are wanting local time, it would be 2020-04-17 09:30:00, same as the input. To come up with 08:30:00 would require more information than you are providing above (e.g. output in some time zone other than that which has a UTC offset of -4h at this local time).
Also it is in general not possible to go from a UTC offset to a time zone name or abbreviation because more than one time zone will generally have the same UTC offset at any point in time.
If the C++20 <chrono> header isn't available for you (to the best of my knowledge it is not yet available anywhere), you can use a free, open-source preview of C+++20 <chrono>. For this problem, one only needs the header-only "date.h" from this preview. And everything is in namespace date instead of namespace std::chrono. It would look like this:
#include "date/date.h"
#include <chrono>
#include <iostream>
#include <sstream>
#include <string>
int
main()
{
using namespace date;
using namespace std;
using namespace std::chrono;
string sToParse = "2020-04-17T09:30:00-04:00";
cout << "raw: " << sToParse << endl;
static const std::string dateTimeFormat { "%Y-%m-%dT%H:%M:%S%z" };
istringstream ss{ sToParse };
sys_seconds dt;
ss >> parse(dateTimeFormat, dt);
cout << dt << '\n';
cout << dt.time_since_epoch() << '\n';
}
Update
With the new knowledge that the "expected human form" of the time should be US Central Time ("America/Chicago" in IANA terms), I'm updating the example code to show how that can be handled.
#include "date/tz.h"
#include <chrono>
#include <iostream>
#include <sstream>
#include <string>
int
main()
{
using namespace date;
using namespace std;
using namespace std::chrono;
string sToParse = "2020-04-17T09:30:00-04:00";
cout << "raw: " << sToParse << endl;
static const std::string dateTimeFormat { "%FT%T%z" };
istringstream ss{ sToParse };
sys_seconds utc;
ss >> parse(dateTimeFormat, utc);
zoned_seconds cst{"America/Chicago", utc};
cout << utc.time_since_epoch() << '\n';
cout << format("%F %T %Z\n", utc);
cout << format("%F %T %Z\n", cst);
}
A few changes above:
A new header is required to handle the time zone issues: "tz.h" (only in the C++20 preview library, not in C++20).
For parsing I've substituted "%Y-%m-%dT%H:%M:%S%z" for "%FT%T%z". These are equivalent. %F is just shorthand for %Y-%m-%d and %T is shorthand for %H:%M:%S. This change is not required.
I've renamed dt to utc to emphasize that this variable holds a UTC time point. This change is not required.
The new line constructs a zoned_time (with seconds precision) with the desired destination time zone ("America/Chicago"), and the UTC time point. This creates an object that knows all about the local time at this time point and in this time zone.
Then everything is printed out using the date::format function and the formatting string "%F %T %Z". %Z is used to output the time zone abbreviation to make the output more readable. In C++20, this will be std::format, and the formatting string will be "{:%F %T %Z}".
The output is now:
raw: 2020-04-17T09:30:00-04:00
1587130200s
2020-04-17 13:30:00 UTC
2020-04-17 08:30:00 CDT
If your computer's current time zone setting happens to be US Central, then the line that constructs zoned_seconds can also look like:
zoned_seconds cst{current_zone(), utc};
Or conversely, you can use this line to find the local time at utc in any time zone which your computer is set to.
Note that whether the time zone is specified with a name such as "America/Chicago", or with current_zone(), any changes of UTC offset within the specified time zone (such as daylight saving time) will be correctly taken into account.
With the preview C+++20 library, the use of the header "tz.h" is not header-only. It requires a single source file, tz.cpp. Here are instructions on how to compile it. But if you are using a fully conforming C++20 <chrono>, then the above will just work by removing #include "date/tz.h", using namespace date;, and adjusting the formatting string as noted in the 5th bullet above.
Related
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 !
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
So right now, the code im using is
using std::chrono::system_clock;
std::time_t tt = system_clock::to_time_t (system_clock::now());
struct std::tm * ptm = std::localtime(&tt);
std::cout << "Current time: " << std::put_time(ptm,"%X") << '\n';
std::this_thread::sleep_for (std::chrono::seconds(7));
It is simple in that this is in a loop, and chrono sleep_for delays the system for however many seconds.
The problem is that it is in the HH:MM:SS format when I really need seconds.milliseconds to show the system clock transaction time. How would I do this? I really just need someone to explain the code, why is it making a struct? And what should I do to change the format? Thanks!
I've got two answers for you:
How to do this next year (in C++20), which isn't implemented today, and
How you can do it today with some minor syntax changes and an open-source 3rd party library.
First 1:
#include <chrono>
#include <iostream>
#include <thread>
int
main()
{
using namespace std::chrono;
auto tp = system_clock::now();
while (true)
{
zoned_time zt{current_zone(), floor<milliseconds>(system_clock::now())};
cout << "Current time: " << std::format("{:%T}", zt) << '\n';
tp += 7s;
std::this_thread::sleep_until (tp);
}
}
This creates a local time using the computer's currently set time zone, with a precision of milliseconds. And then just prints it out with the desired format (%T). I'm using sleep_until instead of sleep_for so that each iteration of the loop doesn't drift off of the desired 7s interval due to loop overhead.
Second 2:
Nobody has C++20 chrono yet, but you can approximate it today with Howard Hinnant's free open source date/time library:
#include "date/tz.h"
#include <chrono>
#include <iostream>
#include <thread>
int
main()
{
using namespace date;
using namespace std::chrono;
auto tp = system_clock::now();
while (true)
{
zoned_time zt{current_zone(), floor<milliseconds>(system_clock::now())};
cout << "Current time: " << format("%T", zt) << '\n';
tp += 7s;
std::this_thread::sleep_until (tp);
}
}
The difference is that the format statement is slightly different, and the library lives in namespace date instead of namespace std::chrono. And there's an extra header to include. And some installation is required to handle the time zones.
If you're happy with a UTC time stamp, instead of a local time stamp, then you can use a header-only version of the same library like this (no installation required):
#include "date/date.h"
#include <iostream>
#include <thread>
int
main()
{
auto tp = std::chrono::system_clock::now();
while (true)
{
using namespace date;
using namespace std::chrono;
std::cout << "Current time: "
<< format("%T", floor<milliseconds>(system_clock::now())) << '\n';
tp += 7s;
std::this_thread::sleep_until (tp);
}
}
I have timestamps in the format (Year.Month.Day) in an XML file.
I need to find out the difference between two timestamps in days.
Sample Timestamps:
<Time Stamp="20181015">
<Time Stamp="20181012">
How can I find the number of days between the above timestamps?
Number of days = date2 - date1. I am considering all the days (don't need to skip weekends or any other day). Time-zone does not matter as well.
PS: I understand that I have to parse the timestamp from XML. I am stuck in the logic after parsing value.
Update-1: std::chrono::year and other such things are part of C++20. But I get a compilation error:
namespace "std::chrono" has no member "year"
There is the old fashioned way:
#include <ctime>
#include <iomanip> // std::get_time
#include <sstream>
// ...
std::string s1 = "20181015";
std::string s2 = "20181012";
std::tm tmb{};
std::istringstream(s1) >> std::get_time(&tmb, "%Y%m%d");
auto t1 = std::mktime(&tmb);
std::istringstream(s2) >> std::get_time(&tmb, "%Y%m%d");
auto t2 = std::mktime(&tmb);
auto no_of_secs = long(std::difftime(t2, t1));
auto no_of_days = no_of_secs / (60 * 60 * 24);
std::cout << "days: " << no_of_days << '\n';
You can use C++20's syntax today (with C++11/14/17) by downloading Howard Hinnant's free, open-source date/time library. Here is what the syntax would look like:
#include "date/date.h"
#include <iostream>
#include <sstream>
int
main()
{
using namespace date;
using namespace std;
istringstream in{"<Time Stamp=\"20181015\">\n<Time Stamp=\"20181012\">"};
const string fmt = " <Time Stamp=\"%Y%m%d\">";
sys_days date1, date2;
in >> parse(fmt, date1) >> parse(fmt, date2);
cout << date2 - date1 << '\n';
int diff = (date2 - date1).count();
cout << diff << '\n';
}
This outputs:
-3d
-3
If you don't need time zone support (as in this example), then date.h is a single header, header-only library. Here is the full documentation.
If you need time zone support, that requires an additional library with a header and source: tz.h/tz.cpp. Here is the documentation for the time zone library.
I have a uint64_t representing the number of nanoseconds since midnight. Would std::chrono allow me to convert this into a meaningful "time", relatively simply?
Also, how would I do it if I have the time since epoch?
For example in such a format:
14:03:27.812374923
And same situation, but when given nanoseconds since epoch? (in case the answer is significantly different)
You could use Howard Hinnant's, free, open-source, header-only library to do this:
#include "date.h"
#include <cstdint>
#include <iostream>
int
main()
{
using namespace std;
using namespace std::chrono;
using namespace date;
uint64_t since_midnight = 50607812374923;
cout << make_time(nanoseconds{since_midnight}) << '\n';
uint64_t since_epoch = 1499522607812374923;
cout << sys_time<nanoseconds>{nanoseconds{since_epoch}} << '\n';
}
This outputs:
14:03:27.812374923
2017-07-08 14:03:27.812374923
Or did you need to take leap seconds into account for since_epoch?
cout << utc_time<nanoseconds>{nanoseconds{since_epoch}} << '\n';
2017-07-08 14:03:00.812374923
For this latter computation, you'll need "tz.h" documented here, and this library is not header only.
I would like to convert an int date like:
20111201
to string:
01DEC2011
Is there a fast date format conversion built into C++ (or maybe a bash system command I can execute instead) to do this or am I stuck making a switch for all of the months?
You could use the strptime to convert your string to a struct tm, then use strftime to reformat it:
#include <ctime>
#include <iostream>
#include <sstream>
int main()
{
std::ostringstream date1;
date1 << 20111201;
struct tm tm;
strptime(date1.str().c_str(), "%Y%m%d", &tm);
char date2[10];
strftime(date2, sizeof(date2), "%d%b%Y", &tm);
std::cout << date1.str() << " -> " << date2 << std::endl;
}
Output is:
20111201 -> 01Dec2011
Just need to convert the Dec to upper case if it's necessary.
Don't use bash here. The way to go is to use Boost in C++ for more reasons than I've time to list here, but ultimately it will be just as fast as most other solutions you'll encounter and unless your functionality is absolutely time critical, it won't make a great deal of difference anyway.
Also, It's going to be far more flexible and maintainable than all those crappy little hard coded date conversion routines that you always encounter.
The following code will do what you want.
#include <iostream>
#include <sstream>
#include <boost/date_time/gregorian/gregorian.hpp>
#include <boost/algorithm/string.hpp>
using namespace boost::gregorian;
using namespace std;
int main(int argc, char **argv)
{
int dateIn = 20111201;
// Read the date in from ISO format as an int.
ostringstream ss;
ss << dateIn;
date d(from_undelimited_string( ss.str() ));
// Set the output format
date_facet *fct = new date_facet("%d%b%Y"); // [1]
locale loc = locale(locale::classic(), fct);
// Render the date as a string;
ss.str("");
ss.imbue(loc);
ss << d;
string dateOut( ss.str() );
boost::to_upper( dateOut );
cout << dateOut << endl;
}
This gives the following output:
01DEC2011
Just changing the format string "%d%b%Y" at ref [1] will change to a different output format but remember I've converted it to uppercase as well.
There's nothing directly built-in, since this format for dates
is relatively rare. The simplest solution here would be to
break the date up into year month day using % and /
operators (e.g. month is value / 100 % 100), then format the
three values normally, using std::ostream, and looking up the
date in a table. (This would obviously require some error
checking, since not all integral values yield valid dates.)
New answer to old question. This answer traffics through the C++11/14 <chrono> library instead of C's tm or boost::date_time. Otherwise it is very similar to the existing answers. It requires this free, open-source library for the parsing and formatting.
#include "tz.h"
#include <iostream>
#include <locale>
#include <sstream>
int
main()
{
auto date1 = 20111201;
std::stringstream stream;
stream.exceptions(std::ios::failbit);
stream << date1;
std::chrono::system_clock::time_point tp;
date::parse(stream, "%Y%m%d", tp);
auto str = date::format("%d%b%Y", tp);
auto& ct = std::use_facet<std::ctype<char>>(std::locale::classic());
ct.toupper(&str.front(), &str.back()+1);
std::cout << str << '\n';
}
I've included stream.exceptions(std::ios::failbit); to noisily detect invalid "integer dates". And I've included old C++98 code to convert the string to uppercase (the locale dance at the end).
01DEC2011
One of the advantages of using a modern C++ date/time library is the ease with which changes can be made. For example, what if now you need to parse the timestamp not with day-precision, but with millisecond precision? Here is how that might be done:
auto date1 = 20111201093357.275L;
std::stringstream stream;
stream.exceptions(std::ios::failbit);
stream << std::fixed << date1;
std::chrono::system_clock::time_point tp;
date::parse(stream, "%Y%m%d%H%M%S", tp);
auto str = date::format("%d%b%Y %T", tp);
auto& ct = std::use_facet<std::ctype<char>>(std::locale::classic());
ct.toupper(&str.front(), &str.back()+1);
std::cout << str << '\n';
which outputs:
01DEC2011 09:33:57.275000
Or perhaps these timestamps are known to originate from Chatham Island off the coast of New Zealand and you need them in UTC. Just add one line after the parse:
tp = date::locate_zone("Pacific/Chatham")->to_sys(tp);
And now the output is:
30NOV2011 19:48:57.275000
Taking into account arbitrary timezones and subsecond precision is currently beyond the capabilities of all other C++ libraries.