網站首頁 編程語言 正文
函數原型如下:
__CRT_INLINE char *__cdecl ctime(const time_t *_Time); __CRT_INLINE struct tm *__cdecl gmtime(const time_t *_Time);
ctime函數
ctime函數可以將當前時間值轉換為字符串格式返回。返回的字符串格式為:Www Mmm dd hh:mm:ss yyyy?其中,Www?表示星期幾,Mmm?是以字母表示的月份,dd?表示一月中的第幾天,hh:mm:ss?表示時間,yyyy?表示年份。
當前時間值需要通過time函數獲取,通過time函數獲取從?1970-01-01 00:00:00?開始到現在所經過的秒數。然后將這個秒數作為參數傳遞到ctime函數中,ctime函數將這個秒數轉換為當前時間格式的字符串返回。
下面通過一個簡單的例子演示一下ctime函數的用法。
#include <stdio.h> #include <stdlib.h> #include <time.h> int main(int argc, char** argv) { time_t now_time; time(&now_time); printf("%s ",ctime(&now_time)); return 0; }
首先通過time函數獲取時間計數值,然后再將這個計數值傳入ctime函數,然后使用?printf函數將?ctime函數返回的字符串打印出來。程序運行結果如下:
gmtime函數
gmtime函數是把日期和時間轉換為格林威治(GMT)時間的函數。將參數time?所指的time_t?結構中的信息轉換成真實世界所使用的時間日期表示方法,然后將結果由結構tm返回。
這個理解起來有點抽象,下面直接通過代碼來演示gmtime函數的用法。
時間結構信息如下:
struct tm { int tm_sec; /* 秒,范圍從 0 到 59 */ int tm_min; /* 分,范圍從 0 到 59 */ int tm_hour; /* 小時,范圍從 0 到 23 */ int tm_mday; /* 一月中的第幾天,范圍從 1 到 31 */ int tm_mon; /* 月份,范圍從 0 到 11 */ int tm_year; /* 自 1900 起的年數 */ int tm_wday; /* 一周中的第幾天,范圍從 0 到 6 */ int tm_yday; /* 一年中的第幾天,范圍從 0 到 365 */ int tm_isdst; /* 夏令時 */ };
這個時間結構的定義在頭文件time.h
中。
#include <stdio.h> #include <stdlib.h> #include <time.h> int main(int argc, char** argv) { char *wday[]= {"Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"}; time_t timep; struct tm *p; time(&timep); p=gmtime(&timep); /* 獲取系統當前時間 */ printf("%d年 %02d月 %02d日",(1900+p->tm_year),(1+p->tm_mon),p->tm_mday); printf("%s %02d:%02d:%02d\n",wday[p->tm_wday],(p->tm_hour+8),p->tm_min,p->tm_sec); return 0; }
系統運行結果如下:
在這里要注意一點,系統返回的年數是從1900年開始計算的,所以在打印年份的時候記得要在年份的值上加上1900。
通過上面兩個函數對吧看出通過ctime函數得到的時間格式是字符串形式的,通過gmtime函數得到的時間格式是結構體形式的。在程序中更加自己的需要選擇來調用不同的函數。
總結
原文鏈接:https://hxydj.blog.csdn.net/article/details/122961953
相關推薦
- 2022-11-21 Go語言實現ssh&scp的方法詳解_Golang
- 2023-03-25 詳解Python中命令行參數argparse的常用命令_python
- 2022-10-17 詳解Go語言中單鏈表的使用_Golang
- 2022-04-11 C語言數組和指針,內存之間的關系_C 語言
- 2022-02-17 出現Presentation Error的解決方法
- 2022-10-02 利用Android封裝一個有趣的Loading組件_Android
- 2022-08-16 一篇文章徹底搞懂Python切片操作_python
- 2023-10-15 自定義帶下箭頭彈出框
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支