File name as current time in seconds since the epoch in c++ - c++

I want to create a new file in c++ having file name as seconds (current time in seconds since the epoch) in FILE_FOLDER.
How can I modify the statement
myfile.open("/FILE_FOLDER/seconds");

Getting the seconds since the epoch as a string is fairly easy:
#include <chrono>
#include <string>
auto now = std::chrono::system_clock::now();
auto now_sec = std::chrono::duration_cast<std::chrono::seconds>(now.time_since_epoch());
auto now_sec_str = std::to_string(now_sec.count());
Or simply:
#include <ctime>
#include <string>
auto now_sec_str = std::to_string(long(std::time(nullptr)));
Then just append that to your folder name:
myfile.open("/FILE_FOLDER/" + now_sec_str);

Related

Why does difference in two chrono time points result in seconds?

I have the following code:
#include <algorithm>
#include <iostream>
#include <iomanip>
#include <ctime>
#include <chrono>
using namespace std;
using namespace std::chrono;
int main()
{
using my_timepoint = time_point<high_resolution_clock, nanoseconds>;
my_timepoint now = system_clock::now();
my_timepoint then = system_clock::now() - seconds{1};
duration<double> my_dur = now - then;
cout << my_dur.count();
}
Here my_timepoint is expressed in nanoseconds still I get output of this code as 1. Why is it not 1e+09? How does the difference in two time points evaluated?
The duration template takes a ratio argument as described here:
https://en.cppreference.com/w/cpp/chrono/duration
The code posted is using the default value (1 tick every 1 second), so naturally when you ask it for count(), it will return just 1, to represent the number of ticks that have elapsed.
You can construct a duration object that uses a different ratio, then you'll get 1e+09:
duration<double, std::ratio<1, 1000000000>> my_dur = now - then;

Number of seconds since midnight

I wrote the below code to get the number of seconds since midnight.
However, I'm not great with the C time date structs. Is there a simpler way of doing this using a standard C++ library?
// Get today's date
time_t aTime = time(NULL);
// Set the time to midnight
struct tm* tm = localtime(&aTime);
tm->tm_sec = 0;
tm->tm_min = 0;
tm->tm_hour = 0;
tm->tm_isdst = -1;
time_t midnight = mktime(tm);
// Create object representing now
struct timespec now;
clock_gettime(CLOCK_REALTIME, &now);
// Number of seconds (now) since Epoch
const uint64_t nowSecsSinceEpoch = now.tv_sec;
// Number of seconds (now) since midnight = seconds (now) since Epoch minus seconds (at midnight) since Epoch
const uint64_t nowSecsSinceMidnight = nowSecsSinceEpoch - midnight;
It depends on if you mean time since midnight UTC, or time since midnight local time, or perhaps in some non-local, far away time zone.
This is also made much easier in C++20. But there exists a preview of the C++20 parts of the <chrono> library that can be used with C++11-17.
Time since midnight UTC
#include <chrono>
#include <iostream>
int
main()
{
using namespace std;
using namespace std::chrono;
auto now = system_clock::now();
auto today = floor<days>(now);
auto tod = duration_cast<seconds>(now - today);
}
This simply gets the current time (UTC), truncates it to a days-precision time_point, and then subtracts the two and truncates that difference to seconds precision.
Time since local midnight
#include <chrono>
#include <iostream>
int
main()
{
using namespace std;
using namespace std::chrono;
auto now = current_zone()->to_local(system_clock::now());
auto today = floor<days>(now);
auto tod = duration_cast<seconds>(now - today);
}
This version finds your computer's currently set local time zone, and then gets the current local time via the time_zone's to_local() member function. And then proceeds as before.
Time since some other midnight
#include <chrono>
#include <iostream>
int
main()
{
using namespace std;
using namespace std::chrono;
auto now = locate_zone("Australia/Sydney")->to_local(system_clock::now());
auto today = floor<days>(now);
auto tod = duration_cast<seconds>(now - today);
}
Finally, this version finds the time_zone associated with Sydney Australia, and then uses that time zone and proceeds as before.
The C++20 preview <chrono> library is free and open-source. It puts everything in namespace date, and in two headers (and one source):
date.h: A header-only library that will do the UTC part, but has no time zone support.
tz.h: For the time zone support. This requires some installation.

is there a way to get utc nanoseconds for a date in uint64_t in c++

I want to get number of nano seconds since epoch in uint64_t for a particular date, is there a function in any c++ library to get it.
If you have access to the C++ 11 libraries, check out the std::chrono library. You can use it to get the milliseconds since the Unix Epoch like this:
#include <chrono>
// ...
using namespace std::chrono;
milliseconds ms = duration_cast< milliseconds >(
system_clock::now().time_since_epoch()
);
You could use Howard Hinnant's free, open-source date/time library which extends std::chrono into the real of calendars:
#include "date.h"
#include <iostream>
int
main()
{
using namespace date;
using namespace std::chrono_literals;
uint64_t k = (sys_days{2017_y/mar/21} + 10h + 27min + 5s +
123456789ns).time_since_epoch().count();
std::cout << k << '\n';
}
Output:
1490092025123456789

How to get timestamp in microseconds in C++?

I have tried this and other codes I found online but they did not work. My IDE is Xcode.
Edit: When I tried the code on the link, the variable long long microseconds always returned 0.
I would like to print the timestamp in this manner: (hour:minute:microseconds). For example, 15:17:09:134613464312.
The method you use is correct.
If you the code between the two now() calls lasts less than a microseconds, microseconds will always be zero, since the number is not a floating point. If you have always zero, that means you need higher resolution (try nanoseconds).
Btw, if you simply want timestamp, you don't want to use this code since it is done to compute elapsed time between two time points. You can try something like this:
auto microseconds = std::chrono::duration_cast<std::chrono::microseconds>
(std::chrono::high_resolution_clock::now().time_since_epoch()).count();
Which is really a timestamp and not a duration.
EDIT: To have the current microseconds count, you can do something like this:
#include <iostream>
#include <chrono>
#include <ctime>
using namespace std;
using namespace std::chrono;
using days = duration<int, ratio_multiply<hours::period, ratio<24> >::type>;
int main() {
system_clock::time_point now = system_clock::now();
system_clock::duration tp = now.time_since_epoch();
days d = duration_cast<days>(tp);
tp -= d;
hours h = duration_cast<hours>(tp);
tp -= h;
minutes m = duration_cast<minutes>(tp);
tp -= m;
seconds s = duration_cast<seconds>(tp);
tp -= s;
cout << tp.count() << "\n";
return 0;
}
This will print the current microseconds count.
Hours:Minutes:Seconds is pretty easy.

How to sleep until next Sunday

How can I sleep until next Sunday using boost? Can i convert boost::gregorian::date object to something that boost::this_thread::sleep_until can handle? Is it possible?
#include <boost/date_time.hpp>
int main()
{
boost::gregorian::date current_date(boost::gregorian::day_clock::local_day());
boost::gregorian::greg_weekday next_sunday_date(boost::gregorian::Sunday);
boost::gregorian::date next_weekday_date = next_weekday(current_date, next_sunday_date);
// ...
}
Here's what I came up with.
Note that I made the code generally more readable. This is important, not just for future maintenance, but also because it will allow you to "see the forest for the trees" - in turn allowing you to remember the important concepts mentally.
At least, that helps me.
Edit DyP contributed a way to use sleep_until (which would behave more accurately in rare circumstances, e.g. where the clock would change during the sleep).
#include <boost/date_time.hpp>
#include <boost/date_time/time_clock.hpp>
#include <iostream>
#include <thread>
#include <chrono>
int main()
{
using namespace boost::gregorian;
using boost::posix_time::ptime;
using clock = boost::posix_time::microsec_clock; // or: boost::posix_time::second_clock;
auto today = date(day_clock::local_day());
auto at_sunday = greg_weekday(Sunday);
auto next_sunday = next_weekday(today, at_sunday);
#if 1
auto as_tm = to_tm(next_sunday);
auto as_time_t = mktime(&as_tm);
auto as_time_point = std::chrono::system_clock::from_time_t(as_time_t);
std::this_thread::sleep_until(as_time_point);
#else
auto duration = (ptime(next_sunday) - clock::local_time());
auto msecs = duration.total_milliseconds();
std::cout << msecs << "\n";
std::this_thread::sleep_for(std::chrono::milliseconds(msecs));
#endif
}
See it compiling on Coliru (obviously times out)
This sounds unstable. What if the user turns the computer off or goes into hibernation, or just does a restart?
I would do this in one of two ways:
Add a scheduled task(or whatever the windows/osx terminology is) / cronjob (linux) and set it to run on Sunday.
Add it to autostart and periodically(once per 10/30/60 minutes) check if it's Sunday.
Both ways handle restart/shut off/hibernation better than sleeping for 5 days.