std::time_point from and to std::string - c++

Am trying to replace some boost::gregorian code using c++20 std::chrono, hoping to remove the boost build depedency. Code is reading and writing to json (using nlohmann) so ability to convert dates to and from std::string is critical.
Using g++ 9.3.0 on Ubuntu 20.04. 2 compile-time erorrs, one on std::chrono::parse() and the second on std::put_time()
For error A on std::chrono::parse(), I see here that calendar support (P0355R7), that includes chrono::parse, is not yet available in gcc libstdc++. Anyone know if this is correct or have a link to an ETA for this? or is there something wrong with how I'm calling parse()?
For error B for std::put_time(): since std:put_time() is documented as c++11 feel like I'm missing something silly here. Also find it strange needing to covert through c's time_t and tm. Is there a better way to convert std::chrono::time_point directly to std::string without resorting to c?
#include <chrono>
#include <string>
#include <sstream>
#include <iostream>
int main(int argc, char *argv[]) {
std::chrono::system_clock::time_point myDate;
//Create time point from string
//Ref: https://en.cppreference.com/w/cpp/chrono/parse
std::stringstream ss;
ss << "2020-05-24";
ss >> std::chrono::parse("%Y-%m-%e", myDate); //error A: ‘parse’ is not a member of ‘std::chrono’
//Write time point to string
//https://en.cppreference.com/w/cpp/io/manip/put_time
//http://cgi.cse.unsw.edu.au/~cs6771/cppreference/en/cpp/chrono/time_point.html
std::string dateString;
std::time_t dateTime = std::chrono::system_clock::to_time_t(myDate);
std::tm tm = *std::localtime(&dateTime);
dateString = std::put_time(&tm, "%Y-%m-%e"); //error B: ‘put_time’ is not a member of ‘std’
//Write out
std::cout << "date: " << dateString << "\n";
return 0;
}

C++20 <chrono> is still under construction for gcc. I've seen no public ETA's for it.
Your syntax for std::chrono::parse looks correct. If you're willing to use a free, open-source, header-only preview of C++20 <chrono> then you can get it to work by adding #include "date/date.h" and using date::parse instead.
Note that the resulting myDate will be 2020-05-24 00:00:00 UTC.
std::put_time lives in the header <iomanip> and is a manipulator. After adding that header and <iostream> you would use it like this:
std::cout << "date: " << std::put_time(&tm, "%Y-%m-%e") << '\n';
If you need the output in a std::string, you will have to stream the manipulator to a std::stringstream first.
C++20 <chrono> will provide an alternative to the C API for formatting:
std::cout << "date: " << std::format("{%Y-%m-%e}", myDate) << '\n';
The preview library also provides this with a slightly altered format string:
std::cout << "date: " << date::format("%Y-%m-%e", myDate) << '\n';

Related

Timestamp conversion using cplusplus [duplicate]

How do I get a uint unix timestamp in C++? I've googled a bit and it seems that most methods are looking for more convoluted ways to represent time. Can't I just get it as a uint?
C++20 introduced a guarantee that time_since_epoch is relative to the UNIX epoch, and cppreference.com gives an example that I've distilled to the relevant code, and changed to units of seconds rather than hours:
#include <iostream>
#include <chrono>
int main()
{
const auto p1 = std::chrono::system_clock::now();
std::cout << "seconds since epoch: "
<< std::chrono::duration_cast<std::chrono::seconds>(
p1.time_since_epoch()).count() << '\n';
}
Using C++17 or earlier, time() is the simplest function - seconds since Epoch, which for Linux and UNIX at least would be the UNIX epoch. Linux manpage here.
The cppreference page linked above gives this example:
#include <ctime>
#include <iostream>
int main()
{
std::time_t result = std::time(nullptr);
std::cout << std::asctime(std::localtime(&result))
<< result << " seconds since the Epoch\n";
}
#include<iostream>
#include<ctime>
int main()
{
std::time_t t = std::time(0); // t is an integer type
std::cout << t << " seconds since 01-Jan-1970\n";
return 0;
}
The most common advice is wrong, you can't just rely on time(). That's used for relative timing: ISO C++ doesn't specify that 1970-01-01T00:00Z is time_t(0)
What's worse is that you can't easily figure it out, either. Sure, you can find the calendar date of time_t(0) with gmtime, but what are you going to do if that's 2000-01-01T00:00Z ? How many seconds were there between 1970-01-01T00:00Z and 2000-01-01T00:00Z? It's certainly no multiple of 60, due to leap seconds.
As this is the first result on google and there's no C++20 answer yet, here's how to use std::chrono to do this:
#include <chrono>
//...
using namespace std::chrono;
int64_t timestamp = duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
In versions of C++ before 20, system_clock's epoch being Unix epoch is a de-facto convention, but it's not standardized. If you're not on C++20, use at your own risk.
#include <iostream>
#include <sys/time.h>
using namespace std;
int main ()
{
unsigned long int sec= time(NULL);
cout<<sec<<endl;
}
I created a global define with more information:
#include <iostream>
#include <ctime>
#include <iomanip>
#define __FILENAME__ (__builtin_strrchr(__FILE__, '/') ? __builtin_strrchr(__FILE__, '/') + 1 : __FILE__) // only show filename and not it's path (less clutter)
#define INFO std::cout << std::put_time(std::localtime(&time_now), "%y-%m-%d %OH:%OM:%OS") << " [INFO] " << __FILENAME__ << "(" << __FUNCTION__ << ":" << __LINE__ << ") >> "
#define ERROR std::cout << std::put_time(std::localtime(&time_now), "%y-%m-%d %OH:%OM:%OS") << " [ERROR] " << __FILENAME__ << "(" << __FUNCTION__ << ":" << __LINE__ << ") >> "
static std::time_t time_now = std::time(nullptr);
Use it like this:
INFO << "Hello world" << std::endl;
ERROR << "Goodbye world" << std::endl;
Sample output:
16-06-23 21:33:19 [INFO] main.cpp(main:6) >> Hello world
16-06-23 21:33:19 [ERROR] main.cpp(main:7) >> Goodbye world
Put these lines in your header file. I find this very useful for debugging, etc.
Windows uses a different epoch and time units: see
Convert Windows Filetime to second in Unix/Linux
What std::time() returns on Windows is (as yet) unknown to me (;-))

Can I avoid going through time_t to print a time_point?

Here's an example adapted from cppreference.com :
#include <iostream>
#include <iomanip>
#include <ctime>
#include <chrono>
int main() {
std::chrono::system_clock::time_point now = std::chrono::system_clock::now();
std::time_t now_c = std::chrono::system_clock::to_time_t(now);
std::cout << "The time was just "
<< std::put_time(std::localtime(&now_c), "%F %T") << '\n';
}
I don't like this. I want to print my time point without having to go through time_t. Can I do so...:
at all?
with an arbitrary format like put_time supports?
Notes:
Standard library solutions are best; non-standard but robust solutions are also relevant.
Not a dupe of this - since I'm also interested in arbitrary format printing; but it should be noted that #HowardHinnant's answer to that one resolves the first part of this one.
Howard Hinnant's library - which has been voted to become part of C++20 - also supports put_time-like formatting.
#include "date/date.h"
#include <iostream>
int
main()
{
std::cout << date::format("%m/%d/%Y %I:%M:%S %p\n", std::chrono::system_clock::now());
}
Example output:
07/22/2018 03:30:35.001865 AM
A partial solution which doesn't allow you a choice of printing format or timezone, thanks to #inf's suggestion, is found in this answer: you can simply pipe a timepoint to the standard output to get a UTC timestamp string for it:
std::cout << std::chrono::system_clock::now() << " UTC\n";
but the question remains open for arbitrary formats.

How to check that timezone exists with boost locale

I need to parse time from string (%Y-%M-%d %H:%m:%s) according to some timezone.
My first idea was to try boost::date_time, however it looks like its database is outdated and timezone detection algorithm is wrong in general. So I decided to try boost::locale. It has ICU backend, so timezone support should be good. I use the following code:
namespace as = boost::locale::as;
void foo(std::string time, std::string timezone) {
auto glob = boost::locale::localization_backend_manager::global();
glob.select("icu"); // select icu backend
boost::locale::generator gen{glob};
auto loc = gen.generate(""); // generate locale with boost facets
auto cal = boost::locale::calendar{loc, timezone};
boost::locale::date_time dt{cal};
std::stringstream ss{time};
ss.imbue(loc);
std::cout.imbue(loc);
ss >> as::ftime("%Y-%m-%d %T") >> as::time_zone(timezone) >> dt;
std::cout << as::time_zone("UTC") << dt << std::endl;
std::cout << as::time_zone(timezone) << dt << std::endl;
}
This works well, however if I pass some invalid timezone name ("foo"), the library accepts it, no exception is thrown, the time is parsed as if it is UTC time. That's not good for me, I want to detect this case somehow, so that I can notify user that the result will not be what he/she expects.
My first idea was to check cal.get_time_zone(), but it always returns the string that was passed to constructor ("foo" in my case), no matter if it's valid or not.
Next, I tried to extract calendar_facet from the generated locale, like so:
const auto &icu_cal = std::use_facet<boost::locale::calendar_facet>(loc);
so that I can access an internal abstract_calendar class. Unfortunately, this line doesn't compile. The reason is that boost/locale/generator.hpp has a static constant with the same name (calendar_facet) in the same boost::locale namespace. The compiler reports that it can not instantiate std::use_facet. Maybe I can move it to a separate compilation unit and avoid including generator.hpp header there, but it looks like a hack for me. Is it a bug or I'm missing something here?
Is there a straightforward way how to validate timezone name with boost::locale? Do you recommend it in general? Thanks for your help.
Edit: here is a minimal example of code that doesn't compile for me
#include <boost/locale.hpp>
int main() {
auto my = boost::locale::localization_backend_manager::global();
my.select("icu");
boost::locale::generator gen{my};
std::use_facet<boost::locale::calendar_facet>(gen.generate(""));
return 0;
}
I compile it like so (on ubuntu 16.04, gcc 5.4):
g++ -std=c++14 -L/usr/lib/x86_64-linux-gnu/ test.cpp -lboost_locale -lboost_date_time
Edit 2: With Sehe's help I managed to get calendar facet from locale and now can I check timezone like this:
int main(int argc, char **argv) {
auto my = boost::locale::localization_backend_manager::global();
my.select("icu");
boost::locale::generator gen{my};
auto ptr = std::unique_ptr<boost::locale::abstract_calendar>(std::use_facet<class boost::locale::calendar_facet>(gen.generate("")).create_calendar());
ptr->set_timezone(argv[1]);
// if ICU backend does not recognize timezone, it sets it to Etc/Unknown
if (ptr->get_timezone() != argv[1]) {
std::cout << "bad timezone " << ptr->get_timezone() << std::endl;
} else {
std::cout << "good timezone " << ptr->get_timezone() << std::endl;
}
return 0;
}
Update: while I managed to make boost locale do what I want on linux, I later faced some weird errors when I ported my code to OS X (it looks like mac doesn't have ICU backend by default...). So, I decided to switch to Howard Hinnant's date library instead. This library is of a high quality, works well on both linux and mac, author is helpful and responsive, so highly recommended.
The fix to the non-compiling sample:
Live On Coliru
#include <boost/locale.hpp>
int main() {
auto my = boost::locale::localization_backend_manager::global();
my.select("icu");
boost::locale::generator gen{my};
std::use_facet<class boost::locale::calendar_facet>(gen.generate(""));
}
Here is an alternative timezone library that may be easier to use:
#include "tz.h"
#include <iostream>
#include <sstream>
int
main(int argc, char **argv)
{
try
{
auto tz = date::locate_zone(argv[1]);
std::cout << "good timezone " << tz->name() << std::endl;
date::local_seconds tp;
std::istringstream in{"2017-09-08 11:30:15"};
in >> date::parse("%Y-%m-%d %H:%M:%S", tp);
auto zt = date::make_zoned(tz, tp);
std::cout << date::format("%Y-%m-%d %T %Z which is ", zt);
std::cout << date::format("%Y-%m-%d %T %Z\n", zt.get_sys_time());
}
catch (std::exception const& e)
{
std::cout << "bad timezone " << e.what() << std::endl;
}
}
Sample output 1:
good timezone America/New_York
2017-09-08 11:30:15 EDT which is 2017-09-08 15:30:15 UTC
Sample output 2:
bad timezone America/New_Yor not found in timezone database

How to convert a boost::ptime to string

I'm having trouble converting a ptime object from boost into a string to be passed in to a function. I have found multiple similar other threads in regards to outputing a boost time object to a string (mostly to cout) but none of what I've found on them are working.
It appears the easiest way is inserting the ptime object into a stringstream and then using the stringstream's string. I have also attempted to imbue the stringstream with a time_facet, as some of the answers on other threads suggest. However, I am unable to create a time_facet object. It gives me the error that the argument list for the class template is missing. What is confusing is the nowhere on the internet have I found any mention of an argument list for time_facet, and even boost's documentation page shows that the default constructor for a time_facet is merely time_facet().
Below is a simple version of what I have tried:
#include <boost/date_time/posix_time/posix_time.hpp>
#include <boost/date_time/posix_time/posix_time_io.hpp>
boost::posix_time::ptime time = boost::posix_time::time_from_string("1981-08-20 08:05:00");
std::stringstream sstream;
sstream << time;
_updateStatement->setString(1, (sql::SQLString)sstream.str());
The insertion of time into the stringstream gives me a bunch of compilation errors in the vein of
error C2220: warning treated as error - no 'object' file generated C:\code\trunk\Development\External\boost\include\boost/date_time/time_facet.hpp(247) :while compiling class template member function 'boost::date_time::time_facet<time_type,CharT>::time_facet(size_t)'
with
[
time_type=boost::posix_time::ptime,
CharT=char
]
despite the fact that I haven't used any time_facet objects.
When I DO try to do this with a time_facet object, I add in
sstream.imbue(std::locale(sstream.getloc(), new boost::date_time::time_facet("%Y-%m-%d %H:%M:%S")));
before inserting the time into the stringstream. The errors for that are that it wants an argument list as mentioned at the top of this post.
Is there perhaps a function in boost that is the reverse of boost::posix_time::time_from_string()? If not, any other help would be appreciated. Thank you.
The Boost.Date_Time library provides the following ptime to std::string conversions within the boost::posix_time namespace:
std::string to_simple_string(ptime) returns a string in the form of YYYY-mmm-DD HH:MM:SS.fffffffff format where mmm is the three character month name.
std::string to_iso_string(ptime) returns a string in the form of YYYYMMDDTHHMMSS,fffffffff where T is the date-time separator.
std::string to_iso_extended_string(ptime) returns a string in the form of YYYY-MM-DDTHH:MM:SS,fffffffff where T is the date-time separator.
Additionally, stream insertion and extraction operators are provided, allowing ptime to be inserted or extracted from a stream. The input and output formats can be customized by constructing facets with various format flags, and then imbuing the stream with the facet.
Based on the compile error (C2220), the compiler is set to treat all warnings as errors. In some cases, the Boost libraries will compile with warnings. Consider assessing the severity of the actual warning, and handling it appropriately from there. For example, if the warning is trivial, it may be acceptable to use a warning pragma to disable or suppress the specific warning.
Here is a complete example demonstrating converting ptime to a string via its provided conversion functions and stream operators.
#include <iostream>
#include <locale>
#include <string>
#include <boost/date_time/posix_time/posix_time.hpp>
#include <boost/date_time/posix_time/posix_time_io.hpp>
int main()
{
const boost::posix_time::ptime time =
boost::posix_time::time_from_string("1981-08-20 08:05:00");
// ptime to string.
const std::string str_time = to_simple_string(time);
std::cout << str_time << std::endl;
// ptime to stringstream to string.
std::stringstream stream;
stream << time;
std::cout << stream.str() << std::endl;
stream.str("");
// Use a facet to display time in a custom format (only hour and minutes).
boost::posix_time::time_facet* facet = new boost::posix_time::time_facet();
facet->format("%H:%M");
stream.imbue(std::locale(std::locale::classic(), facet));
stream << time;
std::cout << stream.str() << std::endl;
}
Which produces the following output:
1981-Aug-20 08:05:00
1981-Aug-20 08:05:00
08:05
My usage using release 1.55
#include <iostream>
#include <boost/date_time/gregorian/gregorian.hpp>
#include <boost/date_time.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
int main()
{
boost::gregorian::date dayte(boost::gregorian::day_clock::local_day());
boost::posix_time::ptime midnight(dayte);
boost::posix_time::ptime
now(boost::posix_time::microsec_clock::local_time());
boost::posix_time::time_duration td = now - midnight;
std::stringstream sstream;
std::cout << dayte << std::endl;
std::cout << dayte.year() << "/" << dayte.month().as_number()
<< "/" << dayte.day() << std::endl;
std::cout << now << std::endl;
std::cout << td << std::endl;
std::cout << td.hours() << "/" << td.minutes() << "/"
<< td.seconds() << "/" << td.fractional_seconds() << std::endl;
sstream << dayte << std::endl;
sstream << dayte.year() << "/" << dayte.month().as_number()
<< "/" << dayte.day() << std::endl;
sstream << now << std::endl;
sstream << td << std::endl;
sstream << td.hours() << "/" << td.minutes() << "/" << td.seconds()
<< "/" << td.fractional_seconds() << std::endl;
std::cout << sstream.str();
}
Results:
2015-Oct-27
2015/10/27
2015-Oct-27 14:25:18.614684
14:25:18.614684
14/25/18/614684
2015-Oct-27
2015/10/27
2015-Oct-27 14:25:18.614684
14:25:18.614684

C++ convert date formats

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.