Search code examples
c++cstrftimectime

Directly setting values of struct tm's attributes not working


Why does asctime(ptr) return nothing? All the variables of the struct have values. Can someone explain why does this happen?

I also tried using strftime but the result was the same.

#include <iostream>
#include <ctime>
#include <new>
//#include <cstdio>

using namespace std;

int main(int argc,char *argv[])
{
    struct tm *ptr=new struct tm;
    //char buf[50];

    ptr->tm_hour=0;
    ptr->tm_mon=0;
    ptr->tm_year=0;
    ptr->tm_mday=0;
    ptr->tm_sec=0;
    ptr->tm_yday=0;
    ptr->tm_isdst=0;
    ptr->tm_min=0;
    ptr->tm_wday=0;

    cout << asctime(ptr);
    //strftime(buf,sizeof(char)*50,"%D",ptr);
    //printf("%s",buf);

    return 0;
}

Solution

  • The below program works. Remove zero with 1 and it will work.

        struct tm *ptr = new struct tm();
    char buf[50];
    
    ptr->tm_hour = 1;
    ptr->tm_mon = 1;
    ptr->tm_year = 1;
    ptr->tm_mday = 1;
    ptr->tm_sec = 1;
    ptr->tm_yday = 1;
    ptr->tm_isdst = 1;
    ptr->tm_min = 1;
    ptr->tm_wday = 1;
    cout << asctime(ptr)
    

    This also works:

     ptr->tm_hour = 0;
    ptr->tm_mon = 0;
    ptr->tm_year = 0;
    ptr->tm_mday = 1;
    ptr->tm_sec = 0;
    ptr->tm_yday = 0;
    ptr->tm_isdst = 0;
    ptr->tm_min = 0;
    ptr->tm_wday = 0;
    
    cout << asctime(ptr);