简体   繁体   中英

Why is C struct tm (time.h) returning the wrong month?

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;
}

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

Change to

tm *myTime = localtime(&present);

And it prints April

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM