【发布时间】:2011-01-19 06:55:32
【问题描述】:
问题很简单“假设我们有一个整数1 ,如何使用strftime显示January为'1 ',2 月 为'2',3 月 为'3' 等等.. . ?”
【问题讨论】:
问题很简单“假设我们有一个整数1 ,如何使用strftime显示January为'1 ',2 月 为'2',3 月 为'3' 等等.. . ?”
【问题讨论】:
struct tm tm = {0};
tm.tm_mon = n - 1;
strftime(s, len, "%B", &tm);
【讨论】:
tm.tm_mon = n-1; /* 范围是 0 .. 11 */
. 而不是->,这是一个常见错误。 (此答案中的代码将起作用。)
#include <stdio.h>
#include <time.h>
size_t monthName( char* buf, size_t size, int month)
{
struct tm t = {0};
t.tm_mon = month - 1; // turn month 1..12 to 0..11 as `struct tm` wants
return strftime( buf, size, "%B", &t);
}
int main(int argc, char* argv[])
{
char buf[10];
monthName( buf, sizeof( buf), 9);
printf( "%s\n", buf);
return 0;
}
【讨论】: