I am updating some old code and probably trying to update in C ++ 11. The following code is how I display the time and date in my program
#include & lt; Iostream & gt; #include & lt; String & gt; # Include & lt; Stdio.h & gt; # Include & lt; Time.h> Const std :: string return_current_time_and_date () const {time_t now = time (0); Structure tm tstruct; Four buff [80]; Tstruct = * local time (and now); Stufftime (buff, size (buf), "% Y-% m-% d% X", and tristrict); Return buff; } I want to output the current time and date in a similar format using std :: chrono (or similar) but to make sure that How to know Any help would be greatly appreciated. Thanks
& lt; Chrono & gt; The library is not related to time only, except for system_clock , which has the ability to change its timers in time_t , so for the dates & Lt; Chrono & gt; Using will not improve things, hopefully we do not do anything like that in a very distant future. He said, you & lt; Chrono & gt; can be used as follows: #include & lt; Chrono & gt; // chrono :: system_clock #include & lt; Ctime & gt; // local time #include & lt; Sstream & gt; // include the string stream # & lt; Iomanip & gt; // put_time #include & lt; String & gt; // string std :: string return_current_time_and_date () {auto now = std :: chrono :: system_clock :: now (); Auto in_time_t = std :: chrono :: system_clock :: to_time_t (now); Std :: stringstream ss; SS & lt; & Lt; Std :: put_time (std :: local time (& in_time_t, "% y-% m-% d% X"); Return ss.str (); } Note that std :: localtime can cause data races localtime_r or similar functions may be available on your platforms Are there. Update:
Using a new version of Howard Hunent, you can write:
#include "date.h" #include & Lt; Chrono & gt; #include & lt; String & gt; # Include & lt; Sstream & gt; Std :: string return_current_time_and_date () {auto now = std :: chrono :: system_clock :: now (); Auto today = date :: floor & lt; Days & gt; (Now); Std :: stringstream ss; SS & lt; & Lt; Today & lt; & Lt; '' & Lt; & Lt; Date :: create_time (now - today) & lt; & Lt; "UTC"; Return ss.str (); } This will print something "2015-07-24 05: 15: 34.043473124 UTC".
On an unrelated note, const objects have become undesirable with C ++ 11; Constant return values can not be taken. I also removed the previous conversion because the previous consultation is valid only for member functions and there is no need to become a member of this function.
No comments:
Post a Comment