C/C++獲取當前系統時間

//方案— 優點:僅使用C標準庫;缺點:只能精確到秒級  

02 #include <time.h>   

03 #include <stdio.h>   

04 int main( void )   

05 {   

06     time_t t = time(0);   

07     char tmp[64];   

08     strftime( tmp, sizeof(tmp), "%Y/%m/%d %X %A 本年第%j天 %z",localtime(&t) );   

09     puts( tmp );   

10     return 0;   

11 }

 

顯示代碼打印1 size_t strftime(char *strDest, size_t maxsize, const char *format, const struct tm *timeptr);


根據格式字符串生成字符串。


顯示代碼打印1 struct tm *localtime(const time_t *timer);

取得當地時間,localtime獲取的結果由結構tm返回
返回的字符串可以依下列的格式而定:
%a 星期幾的縮寫。Eg:Tue 
%A 星期幾的全名。 Eg: Tuesday
%b 月份名稱的縮寫。 
%B 月份名稱的全名。 
%c 本地端日期時間較佳表示字符串。 
%d 用數字表示本月的第幾天 (範圍爲 00 至 31)。日期
%H 用 24 小時制數字表示小時數 (範圍爲 00 至 23)。 
%I 用 12 小時制數字表示小時數 (範圍爲 01 至 12)。 
%j 以數字表示當年度的第幾天 (範圍爲 001 至 366)。 
%m 月份的數字 (範圍由 1 至 12)。
%M 分鐘。 
%p 以 ''AM'' 或 ''PM'' 表示本地端時間。 
%S 秒數。 
%U 數字表示爲本年度的第幾周,第一個星期由第一個週日開始。 
%W 數字表示爲本年度的第幾周,第一個星期由第一個週一開始。 
%w 用數字表示本週的第幾天 ( 0 爲週日)。 
%x 不含時間的日期表示法。 
%X 不含日期的時間表示法。 Eg: 15:26:30
%y 二位數字表示年份 (範圍由 00 至 99)。 
%Y 完整的年份數字表示,即四位數。 Eg:2008
%Z(%z) 時區或名稱縮寫。Eg:中國標準時間 
%% % 字符。 
 

//方案二 優點:能精確到毫秒級;缺點:使用了windows API   

02 #include <windows.h>   

03 #include <stdio.h>   

04 int main( void )   

05 {   

06  SYSTEMTIME sys;   

07  GetLocalTime( &sys );   

08  printf( "%4d/%02d/%02d %02d:%02d:%02d.%03d 星期%1d/n",sys.wYear,sys.wMonth,sys.wDay,sys.wHour,sys.wMinute, sys.wSecond,sys.wMilliseconds,sys.wDayOfWeek);   

09   return 0;  

10 }

 

方案三,優點:利用系統函數,還能修改系統時間  

2 //此文件必須是c++文件  

3 #include<stdlib.h>  

4 #include<iostream>  

5 using namespace std;  

6 void main()  

7 {  

8     system("time");  

9 }

 

 

//方案四,將當前時間折算爲秒級,再通過相應的時間換算即可  

02 //此文件必須是c++文件  

03 #include<iostream>  

04 #include<ctime>  

05 using namespace std;  

06 int main()  

07 {  

08  time_t now_time;  

09  now_time = time(NULL);  

10  cout<<now_time;  

11  return 0;  

12 }

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章