日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

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

發布時間:2025/3/20 编程问答 33 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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中測試。

總結

以上是生活随笔為你收集整理的c语言获取时间并存储,如何在C程序中获取日期和时间值?的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。