Hello!
The following code should print the current UTC and local times, respectively:
#pragma (disable : 4996)
#include <ctime>
using namespace std;
int main()
{
tm* p_current_tm_0 = gmtime(¤t_time);
tm* p_current_tm_ = localtime(¤t_time);
char* current_tm_0 = asctime(p_current_tm_0);
cout << "Current UTC date and time: " << current_tm_0;
char* current_tm_ = asctime(p_current_tm_);
cout << "Current local date and time: " << current_tm_;
}
However, when I run the program, the output is the local time repeated twice.
I do not understand why that is the case.
>Solution :
The problem here is that gmtime and localtime share a single global struct tm and return a pointer to that. Thus, the localtime call overwrites the structure.
Try this instead, which grabs a copy of the structure:
#include <iostream>
#include <ctime>
using namespace std;
int main()
{
time_t current_time = time(NULL);
tm p_current_tm_0 = * gmtime(¤t_time);
tm p_current_tm_ = * localtime(¤t_time);
char* current_tm_0 = asctime(&p_current_tm_0);
cout << "Current UTC date and time: " << current_tm_0;
char* current_tm_ = asctime(&p_current_tm_);
cout << "Current local date and time: " << current_tm_;
}
(Yes, the variable names are no longer accurate, since they aren’t pointers.)
Alternatively, change the order:
tm * p_current_tm_0 = gmtime(¤t_time);
char* current_tm_0 = asctime(p_current_tm_0);
cout << "Current UTC date and time: " << current_tm_0;
tm * p_current_tm_ = localtime(¤t_time);
char* current_tm_ = asctime(p_current_tm_);
cout << "Current local date and time: " << current_tm_;