I am trying to parse a time-of-day string in the form of "HH:MM", and receive back the nanoseconds since midnight.
So long as I provide a date and a time I can successfully parse it, eg:
(I am using Howard Hinnant's date library in lieu of C++20's chrono, as my std library (gcc 11.2) doesn't support this yet)
#include <iostream>
#include <chrono>
#include <date/date.h>
int main()
{
std::string str = "1970-01-01 08:00";
std::string format = "%Y-%m-%d %H:%M";
std::istringstream ss(str);
std::chrono::time_point<std::chrono::system_clock, std::chrono::nanoseconds> t;
ss >> date::parse(format, t);
if (ss.fail()) [[unlikely]]
std::cerr << "parse failed\n";
std::cout << "ns=" << t.time_since_epoch().count() << '\n';
return 0;
}
I see that chrono has a "time of day" class, hh_mm_ss, but I don't see any associated parsing functionality.
Is it possible to parse a time-of-day string using a format, eg, "%H:%M"?
The way to do this is to parse a duration such as nanoseconds and interpret that as "time duration since midnight":
#include <iostream>
#include <chrono>
#include <date/date.h>
int main()
{
std::string str = "08:00";
std::string format = "%H:%M";
std::istringstream ss(str);
std::chrono::nanoseconds t;
ss >> date::parse(format, t);
if (ss.fail()) [[unlikely]]
std::cerr << "parse failed\n";
using date::operator<<;
std::cout << "time of day = " << t << '\n';
}
This involves:
Truncate your string inputs to the desired information.
Change the type of t to nanoseconds.
I used the streaming operator for nanoseconds and changed the formatting so that the output is:
time of day = 28800000000000ns
If you would rather get your original output without the ns suffix, then you can print out t.count(), and in that case there is no need for the using date::operator<<;.
If you want to get really fancy you can create your own custom chrono::time_point that has the semantics of "time of day". That's usually overkill. But if you would like to head that direction, here's some thoughts on it: https://stackoverflow.com/a/56727183/576911.
I have PostgreSQL timestamp string:
2020-07-06 09:30:00.646533
I'm trying to convert it to timeval struct, I tried using this answer, but I'm getting this output:
Thu Jan 1 00:33:40 1970
This is my code:
#include <iostream>
int main()
{
std::string ss("2020-07-06 09:30:00.646533");
auto t = atoll(ss.c_str());
time_t time = atoi(ss.c_str());
std::cout << asctime(gmtime(&time));
return 0;
}
When running with debugger, I see that this line
auto t = atoll(ss.c_str());
isn't working/set time with values.
How can i fix it?
atoll and atoi simply parse integers of various sizes from a string. They aren't great functions to use in general as they have no way of indicating that they have failed to parse the string. std::stoi and friends are the better functions to use. However in this case we don't have a number we have a date string so std::stoi won't work either (but it can at least tell you it didn't work).
c++20 comes with much better date support, until then Howard Hinnant's date library provides the same functionality:
#include "date.h"
#include <iostream>
#include <sstream>
#include <chrono>
int main()
{
std::stringstream ss("2020-07-06 09:30:00.646533");
// convert string to date time
std::chrono::system_clock::time_point time;
ss >> date::parse("%F %T", time);
if (!ss) {
std::cout << "invalid date\n";
return 1;
}
// get the amount of time since the epoch, assumes std::chrono::system_clock uses the same epoch as timeval
auto sinceEpoch = time.time_since_epoch();
// get the whole number of seconds
auto seconds = date::floor<std::chrono::seconds>(sinceEpoch);
// get the remaining microseconds
auto microseconds = std::chrono::duration_cast<std::chrono::microseconds>(sinceEpoch - seconds);
std::cout << seconds.count() << ", " << microseconds.count() << "\n";
return 0;
}
If you must re-invent the wheel you can do it using the pre c++20 standard library:
#include <iostream>
#include <sstream>
#include <chrono>
#include <iomanip>
int main()
{
std::stringstream ss("2020-07-06 09:30:00.646533");
std::tm tm;
// convert string to date time
std::chrono::system_clock::time_point time;
double fraction;
ss >> std::get_time(&tm, "%Y-%m-%d %H:%M:%S") >> fraction;
if (!ss) {
std::cout << "invalid date\n";
return 1;
}
time_t seconds = mktime(&tm);
int64_t microseconds = fraction * 1'000'000;
std::cout << seconds << ", " << microseconds << "\n";
return 0;
}
Note that the microseconds should really be parsed as an integer not a double but you have to be careful to handle strings with different numbers of digits after the decimal point and with leading zeros.
you can use like this:
#include<ctime>
#include<iotream>
int main()
{
std::string ss = "2020-07-06 09:30:00.646533";
auto i = ss.find_first_of('.');
std::string line(ss.begin()+(i+1),ss.end());
std::tm tm = {};
tm.tm_isdst = -1; // <- to set not to use day lghite saveing.
strptime(ss.c_str(), "%F %H:%M:%S", &tm); //<-enter the data to tm
start.tv_sec = mktime(&tm); //<-convert tm to time_t
start.tv_usec = stoi(line); // <- set the usec from the stirng
//IF you want the other why around
strftime(tmbuf, sizeof tmbuf, " %F %H:%M:%S", localtime(&start.tv_sec));
snprintf(buf, sizeof buf, "%s.%06ld", tmbuf, start.tv_usec);
std::cout << tmbuf;
return 0;
}
output:
2020-07-06 09:30:00.646533
How do I parse a RFC3339 timestamp ("1985-04-12T23:20:50.52Z") (i.e. a subset of ISO8601) in C++03? I'm using Boost, but none of the Boost datetime libraries seem to include a function to do this.
The type of the actual time object doesn't matter, as long as I can easily compare it to 'now'. I only care about timestamps in the UTC timezone.
Have limitation of parsing timezone.
#include <sstream>
#include <iostream>
#include <string>
#include <iomanip>
int main() {
std::tm t = {};
std::string s = "2016-01-02T15:04:05+09:00";
int tz_offset = 0;
auto pos = s.find_last_of("+-Z");
if (pos != s.npos) {
std::string zone = s.substr(pos);
tz_offset = std::atoi(zone.c_str());
s.resize(pos);
}
std::stringstream ss(s);
ss >> std::get_time(&t, "%Y-%m-%dT%H:%M:%S");
if (ss.fail()) {
std::cout << "Parse failed\n";
} else {
std::time_t l = std::mktime(&t);
std::tm tm_utc(*std::gmtime(&l));
std::time_t utc = std::mktime(&tm_utc);
tz_offset += (utc - l);
l = std::mktime(&t) - tz_offset;
t = *std::gmtime(&l);
std::cout << std::put_time(&t, "%c") << std::endl;
}
}
Without using Boost, just strptime you can.
Assuming the same _adaptive_parser_ helper posted here: Using boost parse datetime string: With single digit hour format
Note: the samples taken from the RFC link
#include "adaptive_parser.h"
#include <string>
#include <iostream>
int main() {
using namespace mylib::datetime;
adaptive_parser parser;
for (std::string const input : {
"1985-04-12T23:20:50.52Z",
"1996-12-19T16:39:57-08:00",
"1990-12-31T23:59:60Z",
"1990-12-31T15:59:60-08:00",
"1937-01-01T12:00:27.87+00:20",
})
try {
std::cout << "Parsing '" << input << "'\n";
std::cout << " -> epoch " << parser(input).count() << "\n";
} catch(std::exception const& e) {
std::cout << "Exception: " << e.what() << "\n";
}
}
Prints
Parsing '1985-04-12T23:20:50.52Z'
-> epoch 482196050
Parsing '1996-12-19T16:39:57-08:00'
-> epoch 851042397
Parsing '1990-12-31T23:59:60Z'
-> epoch 662688000
Parsing '1990-12-31T15:59:60-08:00'
-> epoch 662688000
Parsing '1937-01-01T12:00:27.87+00:20'
-> epoch -1041335973
Of course, you can limit the number of accepted patterns for the subset you require.
I would like to add timestamps to sensor measurements on an embedded system (Raspberry Pi A+ running ArchLinux). I've found time from time.h but it gives me "second" resolution and I would need at least "milliseconds".
The system would run for a few hours, I'm not concerned about long duration drifts.
How could I get that in C++?
If you have C++11 you can use the <chrono> and <ctime> library like this:
#include <ctime>
#include <string>
#include <chrono>
#include <sstream>
#include <iomanip>
#include <iostream>
// use strftime to format time_t into a "date time"
std::string date_time(std::time_t posix)
{
char buf[20]; // big enough for 2015-07-08 10:06:51\0
std::tm tp = *std::localtime(&posix);
return {buf, std::strftime(buf, sizeof(buf), "%F %T", &tp)};
}
std::string stamp()
{
using namespace std;
using namespace std::chrono;
// get absolute wall time
auto now = system_clock::now();
// find the number of milliseconds
auto ms = duration_cast<milliseconds>(now.time_since_epoch()) % 1000;
// build output string
std::ostringstream oss;
oss.fill('0');
// convert absolute time to time_t seconds
// and convert to "date time"
oss << date_time(system_clock::to_time_t(now));
oss << '.' << setw(3) << ms.count();
return oss.str();
}
int main()
{
std::cout << stamp() << '\n';
}
Output:
2015-07-08 10:13:29.930
Note:
If you want higher resolution you can use microseconds like this:
std::string stamp()
{
using namespace std;
using namespace std::chrono;
auto now = system_clock::now();
// use microseconds % 1000000 now
auto us = duration_cast<microseconds>(now.time_since_epoch()) % 1000000;
std::ostringstream oss;
oss.fill('0');
oss << date_time(system_clock::to_time_t(now));
oss << '.' << setw(6) << us.count();
return oss.str();
}
Output:
2015-07-08 10:20:39.454163
There are a bunch of features available in C++11 chrono header file, please refer this given link
Is there a cross-platform way to get the current date and time in C++?
Since C++ 11 you can use std::chrono::system_clock::now()
Example (copied from en.cppreference.com):
#include <iostream>
#include <chrono>
#include <ctime>
int main()
{
auto start = std::chrono::system_clock::now();
// Some computation here
auto end = std::chrono::system_clock::now();
std::chrono::duration<double> elapsed_seconds = end-start;
std::time_t end_time = std::chrono::system_clock::to_time_t(end);
std::cout << "finished computation at " << std::ctime(&end_time)
<< "elapsed time: " << elapsed_seconds.count() << "s"
<< std::endl;
}
This should print something like this:
finished computation at Mon Oct 2 00:59:08 2017
elapsed time: 1.88232s
C++ shares its date/time functions with C. The tm structure is probably the easiest for a C++ programmer to work with - the following prints today's date:
#include <ctime>
#include <iostream>
int main() {
std::time_t t = std::time(0); // get time now
std::tm* now = std::localtime(&t);
std::cout << (now->tm_year + 1900) << '-'
<< (now->tm_mon + 1) << '-'
<< now->tm_mday
<< "\n";
}
You can try the following cross-platform code to get current date/time:
#include <iostream>
#include <string>
#include <stdio.h>
#include <time.h>
// Get current date/time, format is YYYY-MM-DD.HH:mm:ss
const std::string currentDateTime() {
time_t now = time(0);
struct tm tstruct;
char buf[80];
tstruct = *localtime(&now);
// Visit http://en.cppreference.com/w/cpp/chrono/c/strftime
// for more information about date/time format
strftime(buf, sizeof(buf), "%Y-%m-%d.%X", &tstruct);
return buf;
}
int main() {
std::cout << "currentDateTime()=" << currentDateTime() << std::endl;
getchar(); // wait for keyboard input
}
Output:
currentDateTime()=2012-05-06.21:47:59
Please visit here for more information about date/time format
std C libraries provide time().
This is seconds from the epoch and can be converted to date and H:M:S using standard C functions. Boost also has a time/date library that you can check.
time_t timev;
time(&timev);
New answer for an old question:
The question does not specify in what timezone. There are two reasonable possibilities:
In UTC.
In the computer's local timezone.
For 1, you can use this date library and the following program:
#include "date.h"
#include <iostream>
int
main()
{
using namespace date;
using namespace std::chrono;
std::cout << system_clock::now() << '\n';
}
Which just output for me:
2015-08-18 22:08:18.944211
The date library essentially just adds a streaming operator for std::chrono::system_clock::time_point. It also adds a lot of other nice functionality, but that is not used in this simple program.
If you prefer 2 (the local time), there is a timezone library that builds on top of the date library. Both of these libraries are open source and cross platform, assuming the compiler supports C++11 or C++14.
#include "tz.h"
#include <iostream>
int
main()
{
using namespace date;
using namespace std::chrono;
auto local = make_zoned(current_zone(), system_clock::now());
std::cout << local << '\n';
}
Which for me just output:
2015-08-18 18:08:18.944211 EDT
The result type from make_zoned is a date::zoned_time which is a pairing of a date::time_zone and a std::chrono::system_clock::time_point. This pair represents a local time, but can also represent UTC, depending on how you query it.
With the above output, you can see that my computer is currently in a timezone with a UTC offset of -4h, and an abbreviation of EDT.
If some other timezone is desired, that can also be accomplished. For example to find the current time in Sydney , Australia just change the construction of the variable local to:
auto local = make_zoned("Australia/Sydney", system_clock::now());
And the output changes to:
2015-08-19 08:08:18.944211 AEST
Update for C++20
This library is now largely adopted for C++20. The namespace date is gone and everything is in namespace std::chrono now. And use zoned_time in place of make_time. Drop the headers "date.h" and "tz.h" and just use <chrono>.
#include <chrono>
#include <iostream>
int
main()
{
using namespace std::chrono;
auto local = zoned_time{current_zone(), system_clock::now()};
std::cout << local << '\n'; // 2021-05-03 15:02:44.130182 EDT
}
As I write this, partial implementations are just beginning to emerge on some platforms.
the C++ standard library does not provide a proper date type. C++ inherits the structs and functions for date and time manipulation from C, along with a couple of date/time input and output functions that take into account localization.
// Current date/time based on current system
time_t now = time(0);
// Convert now to tm struct for local timezone
tm* localtm = localtime(&now);
cout << "The local date and time is: " << asctime(localtm) << endl;
// Convert now to tm struct for UTC
tm* gmtm = gmtime(&now);
if (gmtm != NULL) {
cout << "The UTC date and time is: " << asctime(gmtm) << endl;
}
else {
cerr << "Failed to get the UTC date and time" << endl;
return EXIT_FAILURE;
}
auto time = std::time(nullptr);
std::cout << std::put_time(std::localtime(&time), "%F %T%z"); // ISO 8601 format.
Get the current time either using std::time() or std::chrono::system_clock::now() (or another clock type).
std::put_time() (C++11) and strftime() (C) offer a lot of formatters to output those times.
#include <iomanip>
#include <iostream>
int main() {
auto time = std::time(nullptr);
std::cout
// ISO 8601: %Y-%m-%d %H:%M:%S, e.g. 2017-07-31 00:42:00+0200.
<< std::put_time(std::gmtime(&time), "%F %T%z") << '\n'
// %m/%d/%y, e.g. 07/31/17
<< std::put_time(std::gmtime(&time), "%D");
}
The sequence of the formatters matters:
std::cout << std::put_time(std::gmtime(&time), "%c %A %Z") << std::endl;
// Mon Jul 31 00:00:42 2017 Monday GMT
std::cout << std::put_time(std::gmtime(&time), "%Z %c %A") << std::endl;
// GMT Mon Jul 31 00:00:42 2017 Monday
The formatters of strftime() are similar:
char output[100];
if (std::strftime(output, sizeof(output), "%F", std::gmtime(&time))) {
std::cout << output << '\n'; // %Y-%m-%d, e.g. 2017-07-31
}
Often, the capital formatter means "full version" and lowercase means abbreviation (e.g. Y: 2017, y: 17).
Locale settings alter the output:
#include <iomanip>
#include <iostream>
int main() {
auto time = std::time(nullptr);
std::cout << "undef: " << std::put_time(std::gmtime(&time), "%c") << '\n';
std::cout.imbue(std::locale("en_US.utf8"));
std::cout << "en_US: " << std::put_time(std::gmtime(&time), "%c") << '\n';
std::cout.imbue(std::locale("en_GB.utf8"));
std::cout << "en_GB: " << std::put_time(std::gmtime(&time), "%c") << '\n';
std::cout.imbue(std::locale("de_DE.utf8"));
std::cout << "de_DE: " << std::put_time(std::gmtime(&time), "%c") << '\n';
std::cout.imbue(std::locale("ja_JP.utf8"));
std::cout << "ja_JP: " << std::put_time(std::gmtime(&time), "%c") << '\n';
std::cout.imbue(std::locale("ru_RU.utf8"));
std::cout << "ru_RU: " << std::put_time(std::gmtime(&time), "%c");
}
Possible output (Coliru, Compiler Explorer):
undef: Tue Aug 1 08:29:30 2017
en_US: Tue 01 Aug 2017 08:29:30 AM GMT
en_GB: Tue 01 Aug 2017 08:29:30 GMT
de_DE: Di 01 Aug 2017 08:29:30 GMT
ja_JP: 2017年08月01日 08時29分30秒
ru_RU: Вт 01 авг 2017 08:29:30
I've used std::gmtime() for conversion to UTC. std::localtime() is provided to convert to local time.
Heed that asctime()/ctime() which were mentioned in other answers are marked as deprecated now and strftime() should be preferred.
(For fellow googlers)
There is also Boost::date_time :
#include <boost/date_time/posix_time/posix_time.hpp>
boost::posix_time::ptime date_time = boost::posix_time::microsec_clock::universal_time();
#include <stdio.h>
#include <time.h>
int main ()
{
time_t rawtime;
struct tm * timeinfo;
time ( &rawtime );
timeinfo = localtime ( &rawtime );
printf ( "Current local time and date: %s", asctime (timeinfo) );
return 0;
}
Yes and you can do so with formatting rules specified by the currently-imbued locale:
#include <iostream>
#include <iterator>
#include <string>
class timefmt
{
public:
timefmt(std::string fmt)
: format(fmt) { }
friend std::ostream& operator <<(std::ostream &, timefmt const &);
private:
std::string format;
};
std::ostream& operator <<(std::ostream& os, timefmt const& mt)
{
std::ostream::sentry s(os);
if (s)
{
std::time_t t = std::time(0);
std::tm const* tm = std::localtime(&t);
std::ostreambuf_iterator<char> out(os);
std::use_facet<std::time_put<char>>(os.getloc())
.put(out, os, os.fill(),
tm, &mt.format[0], &mt.format[0] + mt.format.size());
}
os.width(0);
return os;
}
int main()
{
std::cout << timefmt("%c");
}
Output: Fri Sep 6 20:33:31 2013
you could use C++ 11 time class:
#include <iostream>
#include <iomanip>
using namespace std;
int main() {
time_t now = chrono::system_clock::to_time_t(chrono::system_clock::now());
cout << put_time(localtime(&now), "%F %T") << endl;
return 0;
}
out put:
2017-08-25 12:30:08
There's always the __TIMESTAMP__ preprocessor macro.
#include <iostream>
using namespace std
void printBuildDateTime () {
cout << __TIMESTAMP__ << endl;
}
int main() {
printBuildDateTime();
}
example: Sun Apr 13 11:28:08 2014
std::ctime
Why was ctime only mentioned in the comments so far?
#include <ctime>
#include <iostream>
int main()
{
std::time_t result = std::time(nullptr);
std::cout << std::ctime(&result);
}
Output
Tue Dec 27 17:21:29 2011
You can use the following code to get the current system date and time in C++ :
#include <iostream>
#include <time.h> //It may be #include <ctime> or any other header file depending upon
// compiler or IDE you're using
using namespace std;
int main() {
// current date/time based on current system
time_t now = time(0);
// convert now to string form
string dt = ctime(&now);
cout << "The local date and time is: " << dt << endl;
return 0;
}
PS: Visit this site for more information.
You can also directly use ctime():
#include <stdio.h>
#include <time.h>
int main ()
{
time_t rawtime;
struct tm * timeinfo;
time ( &rawtime );
printf ( "Current local time and date: %s", ctime (&rawtime) );
return 0;
}
I found this link pretty useful for my implementation:
C++ Date and Time
Here's the code I use in my implementation, to get a clear "YYYYMMDD HHMMSS" output format. The param in is for switching between UTC and local time. You can easily modify my code to suite your need.
#include <iostream>
#include <ctime>
using namespace std;
/**
* This function gets the current date time
* #param useLocalTime true if want to use local time, default to false (UTC)
* #return current datetime in the format of "YYYYMMDD HHMMSS"
*/
string getCurrentDateTime(bool useLocalTime) {
stringstream currentDateTime;
// current date/time based on current system
time_t ttNow = time(0);
tm * ptmNow;
if (useLocalTime)
ptmNow = localtime(&ttNow);
else
ptmNow = gmtime(&ttNow);
currentDateTime << 1900 + ptmNow->tm_year;
//month
if (ptmNow->tm_mon < 9)
//Fill in the leading 0 if less than 10
currentDateTime << "0" << 1 + ptmNow->tm_mon;
else
currentDateTime << (1 + ptmNow->tm_mon);
//day
if (ptmNow->tm_mday < 10)
currentDateTime << "0" << ptmNow->tm_mday << " ";
else
currentDateTime << ptmNow->tm_mday << " ";
//hour
if (ptmNow->tm_hour < 10)
currentDateTime << "0" << ptmNow->tm_hour;
else
currentDateTime << ptmNow->tm_hour;
//min
if (ptmNow->tm_min < 10)
currentDateTime << "0" << ptmNow->tm_min;
else
currentDateTime << ptmNow->tm_min;
//sec
if (ptmNow->tm_sec < 10)
currentDateTime << "0" << ptmNow->tm_sec;
else
currentDateTime << ptmNow->tm_sec;
return currentDateTime.str();
}
Output (UTC, EST):
20161123 000454
20161122 190454
This works with G++ I'm not sure if this helps you.
Program output:
The current time is 11:43:41 am
The current date is 6-18-2015 June Wednesday
Day of month is 17 and the Month of year is 6,
also the day of year is 167 & our Weekday is 3.
The current year is 2015.
Code :
#include <ctime>
#include <iostream>
#include <string>
#include <stdio.h>
#include <time.h>
using namespace std;
const std::string currentTime() {
time_t now = time(0);
struct tm tstruct;
char buf[80];
tstruct = *localtime(&now);
strftime(buf, sizeof(buf), "%H:%M:%S %P", &tstruct);
return buf;
}
const std::string currentDate() {
time_t now = time(0);
struct tm tstruct;
char buf[80];
tstruct = *localtime(&now);
strftime(buf, sizeof(buf), "%B %A ", &tstruct);
return buf;
}
int main() {
cout << "\033[2J\033[1;1H";
std:cout << "The current time is " << currentTime() << std::endl;
time_t t = time(0); // get time now
struct tm * now = localtime( & t );
cout << "The current date is " << now->tm_mon + 1 << '-'
<< (now->tm_mday + 1) << '-'
<< (now->tm_year + 1900)
<< " " << currentDate() << endl;
cout << "Day of month is " << (now->tm_mday)
<< " and the Month of year is " << (now->tm_mon)+1 << "," << endl;
cout << "also the day of year is " << (now->tm_yday)
<< " & our Weekday is " << (now->tm_wday) << "." << endl;
cout << "The current year is " << (now->tm_year)+1900 << "."
<< endl;
return 0;
}
This compiled for me on Linux (RHEL) and Windows (x64) targeting g++ and OpenMP:
#include <ctime>
#include <iostream>
#include <string>
#include <locale>
////////////////////////////////////////////////////////////////////////////////
//
// Reports a time-stamped update to the console; format is:
// Name: Update: Year-Month-Day_of_Month Hour:Minute:Second
//
////////////////////////////////////////////////////////////////////////////////
//
// [string] strName : name of the update object
// [string] strUpdate: update descripton
//
////////////////////////////////////////////////////////////////////////////////
void ReportTimeStamp(string strName, string strUpdate)
{
try
{
#ifdef _WIN64
// Current time
const time_t tStart = time(0);
// Current time structure
struct tm tmStart;
localtime_s(&tmStart, &tStart);
// Report
cout << strName << ": " << strUpdate << ": " << (1900 + tmStart.tm_year) << "-" << tmStart.tm_mon << "-" << tmStart.tm_mday << " " << tmStart.tm_hour << ":" << tmStart.tm_min << ":" << tmStart.tm_sec << "\n\n";
#else
// Current time
const time_t tStart = time(0);
// Current time structure
struct tm* tmStart;
tmStart = localtime(&tStart);
// Report
cout << strName << ": " << strUpdate << ": " << (1900 + tmStart->tm_year) << "-" << tmStart->tm_mon << "-" << tmStart->tm_mday << " " << tmStart->tm_hour << ":" << tmStart->tm_min << ":" << tmStart->tm_sec << "\n\n";
#endif
}
catch (exception ex)
{
cout << "ERROR [ReportTimeStamp] Exception Code: " << ex.what() << "\n";
}
return;
}
The ffead-cpp provides multiple utility classes for various tasks, one such class is the Date class which provides a lot of features right from Date operations to date arithmetic, there's also a Timer class provided for timing operations. You can have a look at the same.
http://www.cplusplus.com/reference/ctime/strftime/
This built-in seems to offer a reasonable set of options.
localtime_s() version:
#include <stdio.h>
#include <time.h>
int main ()
{
time_t current_time;
struct tm local_time;
time ( ¤t_time );
localtime_s(&local_time, ¤t_time);
int Year = local_time.tm_year + 1900;
int Month = local_time.tm_mon + 1;
int Day = local_time.tm_mday;
int Hour = local_time.tm_hour;
int Min = local_time.tm_min;
int Sec = local_time.tm_sec;
return 0;
}
#include <iostream>
#include <chrono>
#include <string>
#pragma warning(disable: 4996)
// Ver: C++ 17
// IDE: Visual Studio
int main() {
using namespace std;
using namespace chrono;
time_point tp = system_clock::now();
time_t tt = system_clock::to_time_t(tp);
cout << "Current time: " << ctime(&tt) << endl;
return 0;
}
Here is the non-deprecated modern C++ solution for getting a timestamp as a std::string for use with e.g. filenames:
std::string get_file_timestamp()
{
const auto now = std::chrono::system_clock::now();
const auto in_time_t = std::chrono::system_clock::to_time_t(now);
std::stringstream output_stream;
struct tm time_info;
const auto errno_value = localtime_s(&time_info, &in_time_t);
if(errno_value != 0)
{
throw std::runtime_error("localtime_s() failed: " + std::to_string(errno_value));
}
output_stream << std::put_time(&time_info, "%Y-%m-%d.%H_%M_%S");
return output_stream.str();
}
You could use boost and chrono library:
#include <iostream>
#include <chrono>
#include <boost/date_time/posix_time/posix_time.hpp>
using boost::posix_time::to_iso_extended_string;
using boost::posix_time::from_time_t;
using std::chrono::system_clock;
int main()
{
auto now = system_clock::now();
std::cout << to_iso_extended_string(from_time_t(system_clock::to_time_t(now)));
}
#include <Windows.h>
void main()
{
//Following is a structure to store date / time
SYSTEMTIME SystemTime, LocalTime;
//To get the local time
int loctime = GetLocalTime(&LocalTime);
//To get the system time
int systime = GetSystemTime(&SystemTime)
}
I needed a way to insert current date-time at every update of a list.
This seems to work well, simply.
#include<bits/stdc++.h>
#include<unistd.h>
using namespace std;
int main()
{ //initialize variables
time_t now;
//blah..blah
/*each time I want the updated stamp*/
now=time(0);cout<<ctime(&now)<<"blah_blah";
}