strftime (C89)
马丁提到过,这是一个例子:
main.c
#include
#include
#include
int main(void) {
time_t t = time(NULL);
struct tm *tm = localtime(&t);
char s[64];
assert(strftime(s, sizeof(s), "%c", tm));
printf("%s\n", s);
return 0;
}
GitHub上游。
编译并运行:
gcc -std=c89 -Wall -Wextra -pedantic -o main.out main.c
./main.out
样本输出:
Thu Apr 14 22:39:03 2016
的%c说明符产生相同的格式ctime。
此函数的一个优点是它返回写入的字节数,以防在生成的字符串过长的情况下更好地控制错误:
返回值
Provided that the result string, including the terminating null byte, does not exceed max bytes, strftime() returns the number of bytes (excluding the terminating null byte) placed in the array s. If the length of the result string (including the terminating null byte) would exceed max bytes, then
strftime() returns 0, and the contents of the array are undefined.
Note that the return value 0 does not necessarily indicate an error. For example, in many locales %p yields an empty string. An empty format string will likewise yield an empty string.
asctime和ctime(C89)
asctime是格式化a的便捷方法struct tm:
main.c
#include
#include
int main(void) {
time_t t = time(NULL);
struct tm *tm = localtime(&t);
printf("%s", asctime(tm));
return 0;
}
样本输出:
Wed Jun 10 16:10:32 2015
而且也有ctime()其标准说是一条捷径:
asctime(localtime())
正如乔纳森·莱夫勒(Jonathan Leffler)所提到的,该格式的缺点是没有时区信息。
POSIX 7将这些功能标记为“过时”,因此可以在以后的版本中将其删除:
标准开发人员决定将asctime()和asctime_r()函数标记为过时,即使asctime()在ISO C标准中,这也可能会导致缓冲区溢出。ISO C标准还提供了strftime()函数,可用于避免这些问题。
这个问题的C ++版本:如何在C ++中获取当前时间和日期?
在Ubuntu 16.04中测试。