日期时间函数(1)-time()gmtime()strftime()localtime()
生活随笔
收集整理的這篇文章主要介紹了
日期时间函数(1)-time()gmtime()strftime()localtime()
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
◆time()
取得當前時間。此函數會返回從公元1970年1月1日的UTC時間從0時0分0秒算起到現在所經過的秒數。如果參數t為非空指針的話, 此函數也會將返回值存到t指針所指的內存。
成功則返回秒數, 失敗則返回((time_t)-1)值, 錯誤原因存于errno中。
#include <time.h> time_t time(time_t *t);例:
#include <time.h> #include <stdio.h>int main() {int seconds = time((time_t *)NULL);printf("%d\n", seconds); return 0; }運行結果:1517968358
◆gmtime()
返回當時時間,不過該函數返回的時間日期未經時區轉換, 而是UTC時間
#include <time.h> struct tm *gmtime(const time_t *timep);例:
#include <time.h> #include <stdio.h>int main() {char *wday[] = {"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"};time_t timep;struct tm *p; time(&timep);p = gmtime(&timep); printf("%d/%d/%d \n", (1900+p->tm_year), (1+p->tm_mon), p->tm_mday);printf("%s %d:%d:%d\n", wday[p->tm_wday], p->tm_hour, p->tm_min, p->tm_sec);return 0; }運行結果:
2018/2/7
Wed 1:55:53
◆localtime()
取得當地目前的時間和日期。與gmtime()函數不同的是,該函數返回的時間日期已經轉換成當地時區。
#include <time.h> struct tm *localtime(const time_t *timep);例:
#include <stdio.h> #include <time.h>int main() {char *wday[] = {"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"};\time_t timep;struct tm *p;time(&timep);// Get local timep = localtime(&timep); printf("%d/%d/%d ", (1900+p->tm_year), (1+p->tm_mon), p->tm_mday); printf("%s %d:%d:%d\n", wday[p->tm_wday], p->tm_hour, p->tm_min, p->tm_sec);return 0; }運行結果:
2018/2/7 Wed 10:0:32
◆strftime()
格式化日期時間。該函數會把結構體tm根據format所指定的字符串格式做轉換,并將轉換后的內容復制到參數s所指的字符串數組中。
#include <time.h> size_t strftime(char *s, size_t max, const char *format,const struct tm *tm);例:
#include <time.h> #include <stdio.h>int main() {char *format[] = {"%I, %M, %S, %p, %m/%d %a", "%x %X %Y", NULL};char buf[30];int i;time_t clock;struct tm *tm;time(&clock);tm = gmtime(&clock);for (i = 0; format[i] != NULL; i++) {strftime(buf, sizeof(buf), format[i], tm);printf("%s=> %s\n", format[i], buf);}return 0; }運行結果:
%I, %M, %S, %p, %m/%d %a=> 02, 04, 53, AM, 02/07 Wed
%x %X %Y=> 02/07/18 02:04:53 2018
?
轉載于:https://www.cnblogs.com/yongdaimi/p/8425303.html
總結
以上是生活随笔為你收集整理的日期时间函数(1)-time()gmtime()strftime()localtime()的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 怎样调整XenServer下面Linux
- 下一篇: CA双向认证的时候,如果一开始下载的证书