2

It is currently April 10th, 2020. I made this integer month to string month converter function in C. It takes in an integer and returns a string. For some reason, it thinks it is March. I investigated into whether the problem was my converter or something else I printed out the myTime->tm_mon and it returned 2 (March) when it should return 3 (April). Could anyone find (what I'm assuming is) my error and point it out to me?

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

typedef struct tm tm;

void *numberToLetters(int month) {
    char *smonth;
    switch (month) {
    case (0):
        smonth = "January";
        break;
    case (1):
        smonth = "February";
        break;
    case (2):
        smonth = "March";
        break;
    case (3):
        smonth = "April";
        break;
    case (4):
        smonth = "May";
        break;
    case (5):
        smonth = "June";
        break;
    case (6):
        smonth = "July";
        break;
    case (7):
        smonth = "August";
        break;
    case (8):
        smonth = "September";
        break;
    case (9):
        smonth = "October";
        break;
    case (10):
        smonth = "November";
        break;
    case (11):
        smonth = "December";
        break;
    default:
        return NULL;
    }
    return smonth;
}

int main() {
    time_t present;
    time(&present);
    tm *myTime = &present;
    void *month = (char *)numberToLetters(myTime->tm_mon);
    printf("%s\n", month);
    return 0;
}
chqrlie
  • 131,814
  • 10
  • 121
  • 189
Serket
  • 3,785
  • 3
  • 14
  • 45
  • 3
    Wait, you cannot just cast `time_t` to a `struct tm`. I think you need to use `localtime()` or `gmtime()`. – Hellmar Becker Apr 10 '20 at 13:25
  • @HellmarBecker you are correct, my mistake. Will update the code – Serket Apr 10 '20 at 13:28
  • `char * numberToLetters(unsigned month){ char *map[] = { "january" ,"february" ,"march" ,"April" ,"May" ,"June" ,"July" ,"August" ,"September" ,"October" ,"November" ,"December" }; return month < 12 ? map[month] : NULL; }` – William Pursell Apr 10 '20 at 13:28
  • 3
    The code shown has too many `void*`s. – pmg Apr 10 '20 at 13:35

1 Answers1

6

time() returns time_t, to convert it to tm structure, you can use localtime()

Change to

tm *myTime = localtime(&present);

And it prints April

Tony Tannous
  • 14,154
  • 10
  • 50
  • 86