Hi all!

I am trying to manage and understand dates with c++, but the output that I am having does not help much.

Basically I would like to adjust a localtime that can be seen in the string "s_prueba_time" to a UTC time (in my case -2 hours in summer and -1 in winter).

But the output I am having from executing this program is completely weird!

Here you have!
??? Mar 30 06:57:57 2010
Tue Mar 30 07:57:57 2010
Local time and date: Tue Mar 30 05:57:57 2010
UTC time and date: Tue Mar 30 03:57:57 2010
The difference are 2 hours

Basically we can see that after calling mktime (which should be the opposite to localtime) the hour from the initial string is changed by one hour!

I am running on a red hat with 2.6.18-194.3.1 kernel.

Also if I run this piece of code on my ubuntu 10.04 laptop the output differs.

I thought that being this functions on the standard c++ library they should work fine so perhaps it is me that is supousing something that it isn't

Could anyone explain me what could be causing my headaches?

Thank you!

#include <ctime>
#include <iostream>
#include <cstdio>

using namespace std;

time_t stot (std::string time);

int main()
  string s_prueba_time = "2010-03-30T06:57:57.715203Z";

  time_t t_prueba_time = stot ( s_prueba_time );

  t_prueba_time -= 7200;

  struct tm tm_local = *localtime( &t_prueba_time );
  struct tm tm_utc = *gmtime( &t_prueba_time );

  cout << "Local time and date: " << asctime( &tm_local );
  cout << "UTC time and date: " << asctime( &tm_utc );

  cout << "The difference are " << tm_local.tm_hour - tm_utc.tm_hour << " hours" << endl;
  return 0;

time_t stot (std::string time) {
  struct tm tInfo;

  if ( !time.empty() ) {
    sscanf(time.c_str(),  "%d-%d-%dT%d:%d:%dZ", &tInfo.tm_year, &tInfo.tm_mon, &tInfo.tm_mday, &tInfo.tm_hour, &tInfo.tm_min, &tInfo.tm_sec);
    tInfo.tm_year -= 1900;

  cout << asctime( &tInfo );

  mktime ( &tInfo );
  cout << asctime( &tInfo );
  //  return timegm( &tInfo );
  return mktime( &tInfo );

Edited 6 Years Ago by tikoti: n/a

Your problem is most likely in stot with the variable tInfo which you use without initialising all its members, specifically tInfo.tm_wday, tInfo.tm_yday and tInfo.tm_isdst.

The first 2 of which can be initialised to 0 they seem to be corrected by mktime although that may just be an implementation feature but they are certainly ignored in creating the output. tInfo.tm_isdst is important because it relates to day-light savings time being in effect.

You are absolutely right!

It is fixed by just adding the following lines just before the mktime call

tInfo.tm_wday = 0;
  tInfo.tm_yday = 0;
  tInfo.tm_isdst = -1;

It was freaking me out and I wasn't going to see the flaw any time soon.

Thank you so much,

This article has been dead for over six months. Start a new discussion instead.