0

I need to find the weekday from the given date; I have following code but does not work

int day;
char *str ="25/02/2014";  
struct tm tm;

if (strptime(str, "%d/%m/%Y", &tm) != NULL)
{
    time_t t = mktime(&tm);
    day = localtime(&t)->tm_wday;
    return day;
}

What am I doing wrong here?

Enigma
  • 1,247
  • 3
  • 20
  • 51
Thulasi
  • 23
  • 6
  • This is a similar question http://stackoverflow.com/questions/5797814/date-to-day-of-the-week-algorithm – Mykle Nero Feb 27 '14 at 12:49
  • Does this compile ? Here it doesn't unless you replace `struct tm *tm;` by `struct tm tm;` – Jabberwocky Feb 27 '14 at 13:06
  • Even after changing struct tm tm ; the result of weekday is not good .The result of day is always 4 ("27/02/2014") – Thulasi Feb 27 '14 at 13:15
  • I reran this with `struct tm * tm;` but removed the `&` from every `&tm`, and I'm getting results: 4 for 27/02/2014, and 2 for 25/02/2014. – Clark Kent Feb 27 '14 at 13:21
  • if you use `struct tm *tm` and you don't initialize to `NULL` then `tm` points to some invalid address and when the address of that invalid memory location you are passing to `strptime` it fills that memory with data. In this case the behavior will be undefined. – rajenpandit Feb 27 '14 at 13:48
  • @rajenpandit: with `struct tm *tm = NULL` it will crash also because NULL is also an invalid address. – Jabberwocky Feb 27 '14 at 14:11
  • @MichaelWalz: as per `@Saviour Self` the code is returning the expected result by using `struct tm *tm`. It is happening because `tm` is not initialized with `NULL` otherwise program would have crashed. – rajenpandit Feb 27 '14 at 14:16
  • @rajenpandit: ok, so it just runs because he is lucky. – Jabberwocky Feb 27 '14 at 14:20
  • After assigining `struct tm tm = {0};` the program gave me correct result – Thulasi Feb 28 '14 at 09:07

2 Answers2

2

You should take struct tm tm; instead of struct tm * tm;

you need to initialize tm by using memset(&tm,0x00,sizeof(tm)); otherwise mktime will return -1

rajenpandit
  • 1,265
  • 1
  • 15
  • 21
  • With `memset(&tm, 0, sizeof tm)`, is not `isdst` field better set to -1 than left at 0? (I suppose it makes little difference though as DST changes at midnight (h:m:s == 0:00:00) are rare.) – chux - Reinstate Monica Feb 27 '14 at 16:03
0

The result 4 for the date 27/02/2014 is correct, see time.h

Description
...
int tm_wday Day of week [0,6] (Sunday =0).

Sunday is 0, Monday = 1, Tuesday = 2, Wednesday = 3 and Thursday = 4, ...

Olaf Dietsche
  • 72,253
  • 8
  • 102
  • 198