How to convert dd-mmm-yyyy and now() to days? - c++

I need convert a dd-mmm-year string to epoch days to do some simple math. Specifically, calculate the number of days from now() to the date of the string.
I'm looking at <chrono> and <ctime> but am not seeing an obvious way to do that? How do you convert dd-mmm-year and now() to epoch days?

This can easily be done with this free, open-source, header-only preview of C++20 , which works with C++11/14/17:
#include "date/date.h"
#include <iostream>
#include <sstream>
int
main()
{
using namespace date;
using namespace std;
using namespace std::chrono;
string s1 = "25-Mar-2021";
string s2 = "20-Jul-2021";
istringstream in{s1};
in.exceptions(ios::failbit);
sys_days t1;
in >> parse("%d-%b-%Y", t1);
in.str(s2);
in.clear();
sys_days t2;
in >> parse("%d-%b-%Y", t2);
cout << t2 - t1 << '\n';
}
sys_days is a type alias for std::chrono::time_point<system_clock, duration<int, ratio<86400>>>. But you can think of it as a count of days since since 1970-01-01.
The program above outputs:
117d
The type of the expression t2 - t1 is std::chrono::duration<int, ratio<86400>>.
Here is a live example you can experiment with.
Edit:
You can convert durations (such as t2 - t1) to a signed integral type by using the .count() member function:
auto i = (t2 - t1).count(); // 117
Another way to do it is to divide by days{1}:
auto i = (t2 - t1)/days{1}; // 117
This latter technique gives those who know dimensional analysis a warm fuzzy feeling. :-)
You can convert std::chrono::system_clock::now() to type sys_days like this:
auto t2 = floor<days>(system_clock::now());
This gives the current date according to UTC. If you need the current date according to some other time zone (such as the computer's local time zone setting), then that involves an additional library (at the same link) which is not header-only and involves some installation. In that case one would work in terms of local_days instead of sys_days:
#include "date/tz.h"
#include <iostream>
#include <sstream>
int
main()
{
using namespace date;
using namespace std;
using namespace std::chrono;
string s1 = "25-Mar-2021";
istringstream in{s1};
in.exceptions(ios::failbit);
local_days t1;
in >> parse("%d-%b-%Y", t1);
auto t2 = floor<days>(current_zone()->to_local(system_clock::now()));
cout << t2 - t1 << '\n';
}
Output (currently):
1d

Related

How do I convert a string back into a time_point?

I am taking a system_clock time_point, converting it to a string, and then saving it to a configuration file.
Now I want to read that config file and turn the string back into a time point so that I can calculate the difference in time between two time points.
void SaveLastShuffleTime() {
m_lastShuffleTime = std::chrono::system_clock::now();
auto m_lastShuffleTimeTimeT = std::chrono::system_clock::to_time_t(m_lastShuffleTimeTimepoint);
stringstream m_lastShuffeTimeSS;
m_lastShuffeTimeSS << std::put_time(std::localtime(&m_lastShuffleTimeTimeT), "%Y-%m-%d %X");
m_deviceStateSettings.UpdateDeviceStateSettings(LAST_SHUFFLE_TIME, m_lastShuffeTimeSS.str());
}
void CompareLastShuffleTime() {
m _currentShuffleTime = std::chrono::system_clock::now();
/* READ CONFIG FILE AND CONVERT BACK TO TIME POINT */
int timeSinceLastShuffle = (duration_cast<minutes>(m_currentShuffleTime - m_oldShuffleTime)).count();
}
Please let me know if this is viable. The alternative is to save the timepoint as an integer but I would prefer not to do that.
Thanks
I recommend outputting UTC as opposed to local time so that the difference between timestamps isn't altered by UTC offset jumps (e.g. daylight saving).
C++20 makes this very easy, and allows timestamps with subsecond precision:
#include <cassert>
#include <chrono>
#include <iostream>
#include <sstream>
int
main()
{
using namespace std;
using namespace std::chrono;
stringstream s;
auto tp = system_clock::now();
auto tp_save = tp;
s << tp << '\n'; // Write it out
tp = {}; // Zero out the timestamp
s >> parse("%F %T", tp); // Parse it back in
assert(tp == tp_save); // Make sure it is the same
std::cout << s.str(); // This is what was formatted/parsed
}
Example output:
2021-06-17 16:10:10.562738
Vendors are still working on getting this out. But you can use this syntax today with C++11/14/17 and a free, open-source, header-only preview of this part of C++20.1
Just add:
#include "date/date.h"
using namespace date;
and the above works with the preview library.
1 Full disclosure: I am the lead author of this library. I am not pursuing any financial gain from this effort. But sometimes people get grumpy if I don't fully disclose this information.
You could use cctz library. It provides convenient functions for formatting timepoint cctz::format to a string and parsing cctz::parse from a string. And also for working with timezones. Example:
#include <chrono>
#include <iostream>
#include <string>
#include "cctz/time_zone.h"
int main() {
const std::chrono::system_clock::time_point now =
std::chrono::system_clock::now();
std::string now_str =
cctz::format("%Y-%m-%d %H:%M:%S%z", now, cctz::utc_time_zone());
std::cout << now_str << std::endl;
std::chrono::system_clock::time_point tp;
const bool ok =
cctz::parse("%Y-%m-%d %H:%M:%S%z", now_str, cctz::utc_time_zone(), &tp);
if (!ok)
return -1;
}
std::istringstream ss(str);
tm t;
ss >> std::get_time(&t, "%Y-%m-%dT%H:%M:%S");
std::time_t tt = std::mktime(&t);
/// If you don't need UTC time, just comment out the line below.
tt = std::mktime(std::gmtime(&tt));
return std::chrono::system_clock::from_time_t(tt);

Convert a string with micro second precision to a chrono time_point

This is a quite trivial question. But I couldn't find a trivial answer for this.
I have a timestamp string with microsecond precision, say, 20:38:42.444491. How do I convert this into a proper time object so that I can use it in time comparisons etc...
I was trying to use the date lib by HowardHinnant. However I am not sure how to use it only with a timestamp.
e.g.
#include <iostream>
#include "date.h"
using namespace std;
// This works fine
chrono::system_clock::time_point makeDateTime(const string& s) {
istringstream in{s};
chrono::system_clock::time_point tp;
in >> date::parse("%d/%m/%y %T", tp);
return tp;
}
// This always returns epoch. How to fix this ?
chrono::system_clock::time_point makeTime(const string& s) {
istringstream in{s};
chrono::system_clock::time_point tp;
in >> date::parse("%T", tp);
return tp;
}
int main() {
auto a = makeDateTime("30/03/09 16:31:32.121567");
cout << a.time_since_epoch().count() << endl; // 1238430692121567000
auto b = makeTime("16:31:32.121567");
cout << b.time_since_epoch().count() << endl; // 0
return 0;
}
As shown, I can correctly parse a date-time stamp. But I need to know how to handle it if I only have a time (without a date).
With just a time, you've got a couple of options. But you should definitely not put "just a time" into a system_clock::time_point. The reason for this is that system_clock::time_point has a specific meaning: This measures the time since (or before) 1970-01-01 00:00:00 UTC, excluding leap seconds.
To be fair, this meaning is absent in C++11/14/17, and is only specified in C++20. However all implementations followed this convention in C++11/14/17.
You could store "time of day" in a duration such as microseconds. Then in your code you simply interpret this duration as time elapsed since midnight, where you get to define "midnight" (local midnight? UTC? etc.).
std::chrono::microseconds
makeTime(std::string s)
{
using namespace std;
using namespace std::chrono;
istringstream in{move(s)};
microseconds tp;
in >> date::parse("%T", tp);
return tp;
}
The above solution is simple, and that is good. But it is possible that this "time of day" could be accidentally mixed up with some other duration that doesn't mean "time of day" in a way that would cause logic errors in your program.
To make the above more type-safe, you could create a "time of day" clock:
struct time_of_day
{
using duration = std::chrono::microseconds;
using rep = duration::rep;
using period = duration::period;
using time_point = std::chrono::time_point<time_of_day>;
static constexpr bool is_steady = false;
static
time_point
now()
{
using namespace date;
using namespace std::chrono;
auto t_sys = floor<microseconds>(system_clock::now());
return time_point{t_sys - floor<days>(t_sys)};
};
};
time_of_day::time_point
makeTime(std::string s)
{
using namespace std;
using namespace std::chrono;
istringstream in{move(s)};
microseconds d;
in >> date::parse("%T", d);
return time_of_day::time_point{d};
}
Above I've defined midnight as UTC just to simplify the demonstration.
The time_of_day solution isn't necessarily better. The programmer should decide if the extra complexity cost justifies the type safety benefit.

how can i compare a start time with the system clock using ctime/chrono libaray

I'm running into a error trying to compile the program with conversion from double to int. What I want is to be able to display out the difference not just in seconds but in hours/minutes/seconds but I can't think of how to make the difftime work. If there is a better option like using chrono, I would appreciate the help.
#include <chrono>
#include <ctime>
#include <iomanip>
#include <iostream>
int main() {
std::tm now{},;
std::chrono::system_clock::time_point cc;
std::cout << "enter\nyear month day\n";
std::cin >> now.tm_year >> now.tm_mon >> now.tm_mday;
now.tm_year -= 1900;
now.tm_mon -= 1;
std::time_t n = std::mktime(&now);
cc = std::chrono::system_clock::from_time_t(n);
n = std::chrono::system_clock::to_time_t(cc);
std::cout << std::put_time(std::localtime(&n), "%FT%T") << "\n";
std::time_t system_time = time(nullptr);
std::cout << asctime(localtime(&system_time));
double fc = difftime(system_time, mktime(&now));
std::cout << "time diff "<< fc << endl;
}
You should checkout the date lib from howard hinnant.
https://github.com/HowardHinnant/date
The tz lib in it Can do your local time diff calculation in without converting it to utc. (normally you should always convert to utc before calculation, because of the daylight saving time) It also contains format functions to stream it in hour min sec format.
The better way of doing it is using a steady_clock instead of system_clock.
I don't know what your task is but you may use another class such as Stopwatch to generate elapsed time.
#include <chrono>
#include <ctime>
class StopWatch {
private:
chrono::time_point<chrono::steady_clock> start;
public:
void reset() { start = chrono::steady_clock::now(); }
StopWatch() { reset(); }
double elapsedSeconds() {
chrono::duration<double> d = chrono::steady_clock::now() - start;
return chrono::duration_cast<chrono::microseconds>(d).count() / 1000000.;
}};
After that, you can simply use Stopwatch:
int main(void){
Stopwatch s;
cout<<s.elapsedSeconds();
}

Get time difference from specific day

I am trying to find some utility in the chrono namespace to provide to my application the same feature I had in my C# program. What I need to do is to compute the time difference between to specific dates, but I can't find anything this specific. For example following is my C# code:
var startDate = new DateTime(2000, 1, 1);
int diffDays = (DateTime.Today.Date - startDate.Date).Days;
return diffDays.ToString();
Is there any equivalent function in C++?
// system_clock::from_time_t
#include <iostream>
#include <ctime>
#include <ratio>
#include <chrono>
int main ()
{
using namespace std::chrono;
// create tm with 1/1/2000:
std::tm timeinfo = std::tm();
timeinfo.tm_year = 100; // year: 2000
timeinfo.tm_mon = 0; // month: january
timeinfo.tm_mday = 1; // day: 1st
std::time_t tt = std::mktime (&timeinfo);
system_clock::time_point tp = system_clock::from_time_t (tt);
system_clock::duration d = system_clock::now() - tp;
// convert to number of days:
typedef duration<int,std::ratio<60*60*24>> days_type;
days_type ndays = duration_cast<days_type> (d);
// display result:
std::cout << ndays.count() << " days have passed since 1/1/2000";
std::cout << std::endl;
return 0;
}
Credits: http://www.cplusplus.com/reference/chrono/system_clock/from_time_t/
Here's an easier way to do this using this header-only open source lib:
#include "date.h"
#include <iostream>
int
main()
{
using namespace date;
using namespace std::chrono;
auto startDate = 2000_y/jan/1;
auto diffDays = floor<days>(system_clock::now()) - sys_days{startDate};
std::cout << diffDays.count() << '\n';
}
Currently outputs:
6138
Here is a wandbox link where you can paste the above code and try it out yourself using various versions of gcc and clang.

convert Date to time in millisecond in c++?

I have a requirement where I have to convert given string in date time format to milliseconds from epoch.
In Javascript there is date to time conversion api but in c++ I couldn't find anything as such.
Input would look like '2016-Mar-15 09:23:58.665068'
output should be in milliseconds say 14520000785.
I have tried looking into boost but still couldn't find(or understand) how to do?
Also, going through google I find the other way round i.e. converting milliseconds to date format but not what I require nor any helpful post for same.
Any help will be much appreciated.
Using only standard library features:
#include <ctime>
#include <chrono>
#include <iostream>
int main()
{
std::tm tm = {};
const char* snext = ::strptime("2016-Mar-15 09:23:58.665068", "%Y-%b-%d %H:%M:%S", &tm);
auto time_point = std::chrono::system_clock::from_time_t(std::mktime(&tm));
long long duration_ms = time_point.time_since_epoch() / std::chrono::milliseconds(1) + std::atof(snext) * 1000.0f;
std::cout << duration_ms << std::endl;
}
Prints: 1458033838665
See std::chrono::system_clock::now and std::chrono::milliseconds.
Most straightforward would be to just spell it out:
auto pt = boost::lexical_cast<ptime>("2016-Mar-15 09:23:58.665068");
std::cout << (pt - ptime { {1970,0,0}, {} }).total_milliseconds();
Live On Coliru
#include <boost/date_time/posix_time/posix_time.hpp>
#include <boost/date_time/posix_time/posix_time_io.hpp>
#include <boost/date_time.hpp>
#include <sstream>
int main() {
using boost::posix_time::ptime;
ptime pt;
{
std::istringstream iss("2016-Mar-15 09:23:58.665068");
auto* f = new boost::posix_time::time_input_facet("%Y-%b-%d %H:%M:%S%f");
std::locale loc(std::locale(""), f);
iss.imbue(loc);
iss >> pt;
}
std::cout << pt << " " << (pt - ptime{{1970,1,1},{}}).total_milliseconds();
}
Prints
2016-Mar-15 09:23:58.665068 1458033838665
Of course, extract the parsing in a helper function. Keep the locale around for reuse etc.