Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

std :: gmtime does not return UTC time

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(&current_time);
 tm* p_current_tm_ = localtime(&current_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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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(&current_time);
    tm p_current_tm_ = * localtime(&current_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(&current_time);
    char* current_tm_0 = asctime(p_current_tm_0);
    cout << "Current UTC date and time: " << current_tm_0;

    tm * p_current_tm_ = localtime(&current_time);
    char* current_tm_ = asctime(p_current_tm_);
    cout << "Current local date and time: " << current_tm_;
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading