2

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;
}
manlio
  • 18,345
  • 14
  • 76
  • 126
MattSt
  • 1,024
  • 2
  • 16
  • 35

2 Answers2

2

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);
Spanky
  • 1,070
  • 6
  • 11
  • aren't zeros valid values for all the attributes? Why is it not working with zeros? – MattSt Jun 11 '15 at 10:00
  • AFAIK day and month parameter can not be set to zero. I would suggest to do some google to do some find out – Spanky Jun 11 '15 at 10:04
  • @matts : Edited the answer!! – Spanky Jun 11 '15 at 10:04
  • 1
    @Spanky: the encoding for month is 0 = January to 11 = December (so you can have an array of month names, without a dummy entry at index 0). Day of month should be 1..31. Setting `tm_year = 0` implies year 1900; the year is offset by 1900. It might be informative to run `mktime(ptr);` and then print the structure; that normalizes the values. – Jonathan Leffler Jun 11 '15 at 14:36
1

The behavior of asctime is undefined if any member of struct tm is outside its normal range.

Especially the behavior is undefined if the calendar day is less than 0 (some implementations handle tm_mday==0 as meaning the last day of the preceding month).

Take a look at http://en.cppreference.com/w/cpp/chrono/c/asctime and http://en.cppreference.com/w/cpp/chrono/c/tm for further details.

manlio
  • 18,345
  • 14
  • 76
  • 126