首页 > 解决方案 > 为什么 C struct tm (time.h) 返回错误的月份?

问题描述

现在是 2020 年 4 月 10 日。我在 C 中制作了这个整数月份到字符串月份的转换器函数。它接受一个整数并返回一个字符串。由于某种原因,它认为是三月。我调查了问题是我的转换器还是我打印出来的其他东西myTime->tm_mon,它2在应该返回3(4 月)时返回(3 月)。任何人都可以找到(我假设是)我的错误并向我指出吗?

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

标签: ctimectime

解决方案


time()返回time_t,将其转换为tm结构,您可以使用localtime()

改成

tm *myTime = localtime(&present);

它打印四月


推荐阅读