【问题标题】:Why is C struct tm (time.h) returning the wrong month?为什么 C struct tm (time.h) 返回错误的月份?
【发布时间】:2020-07-23 06:09:44
【问题描述】:

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

#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_t 转换为struct tm。我认为您需要使用localtime()gmtime()
  • @HellmarBecker 你是对的,我的错。将更新代码
  • char * numberToLetters(unsigned month){ char *map[] = { "january" ,"february" ,"march" ,"April" ,"May" ,"June" ,"July" ,"August" ,"September" ,"October" ,"November" ,"December" }; return month &lt; 12 ? map[month] : NULL; }
  • 显示的代码有太多void*s。

标签: c time ctime


【解决方案1】:

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

改成

tm *myTime = localtime(&present);

它打印四月

【讨论】:

    猜你喜欢
    • 2016-05-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多