为什么 C struct tm (time.h) 返回错误的月份?
Why is C struct tm (time.h) returning the wrong month?
目前是 2020 年 4 月 10 日。我在 C 中制作了这个整数月到字符串月的转换器函数。它接受一个整数和 returns 一个字符串。出于某种原因,它认为现在是 3 月。我调查了问题是我的转换器还是其他问题我打印了 myTime->tm_mon
并且它 returned 2
(三月)当它应该 return 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;
}
time() returns time_t, to convert it to tm structure, you can use localtime()
改为
tm *myTime = localtime(&present);
并打印四月
目前是 2020 年 4 月 10 日。我在 C 中制作了这个整数月到字符串月的转换器函数。它接受一个整数和 returns 一个字符串。出于某种原因,它认为现在是 3 月。我调查了问题是我的转换器还是其他问题我打印了 myTime->tm_mon
并且它 returned 2
(三月)当它应该 return 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;
}
time() returns time_t, to convert it to tm structure, you can use localtime()
改为
tm *myTime = localtime(&present);
并打印四月