Reputation: 94
I have this simple piece of code
#include <iostream>
#include <ctime>
using namespace std;
int main()
{
time_t now = time(0);
tm timeDate;
strptime("2023-2-10 15:03","%Y-%m-%d %H:%M", &timeDate);
time_t time_input = mktime(&timeDate);
char* dt = ctime(&now);
char* dt2 = ctime(&time_input);
cout << "The local date and time is: " << dt << endl;
cout << "The input date and time is: " << dt2 << endl;
return 0;
}
that should print those two dates. But I receive the same date according to which is processed first.
The local date and time is: Fri Feb 10 15:03:00 2023
The input date and time is: Fri Feb 10 15:03:00 2023
or
The local date and time is: Mon Feb 13 12:32:17 2023
The input date and time is: Mon Feb 13 12:32:17 2023
Upvotes: 1
Views: 80
Reputation: 30817
The ctime
function is not reentrant, which means that you cannot safely call it multiple times and reuse the same output.
Instead, use the ctime_r
function which writes its output into a buffer you supply and then the times will be different.
Upvotes: 5