c语言获取时间并存储,如何在C程序中获取日期和时间值?

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中测试。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值