1. 獲取時間戳:
time_t rawtime;
time(&rawtime); //結果是時間戳
2. 將時間戳轉為 char* 類型的日期 Www Mmm dd hh:mm:ss yyyy
1 /* ctime example */ 2 #include <stdio.h> 3 #include <time.h> 4 #include <iostream> 5 6 using namespace std; 7 8 int main () 9 { 10 time_t rawtime; 11 12 time ( &rawtime ); 13 printf("%ld\n", &rawtime); 14 printf ( "The current local time is: %s", ctime (&rawtime) ); 15 16 char * time = ctime(&rawtime); 17 //ctime(&rawtime) : time_t/timestampe -> "Www Mmm dd hh:mm:ss yyyy" format 18 cout<< time << endl; 19 printf("%s", asctime(gmtime(&rawtime)));// asctime(gmtime(&rawtime)) = ctime(&rawtime); 20 //here gmtime(&rawtime) : time_t(timpstampe) -> struct tm 21 //here asctime(gmtime) : struct tm -> "Www Mmm dd hh:mm:ss yyyy" format 22 23 24 struct tm * ptm; 25 ptm = gmtime(&rawtime); 26 27 cout<<(ptm->tm_year + 1900)<<"year "<<(ptm->tm_mon + 1)<<"month "<<(ptm->tm_mday)<<"day "<<(ptm 28 ->tm_hour)<<":"<<(ptm->tm_min)<<":"<<(ptm->tm_sec)<<endl; 29 30 31 return 0; 32 }
結果:
134507764 //time ( &rawtime ); printf("%ld\n", &rawtime);
The current local time is: Mon Jul 9 15:17:03 2012 //printf ( "The current local time is: %s", ctime (&rawtime) );
Mon Jul 9 15:17:03 2012 //char * time = ctime(&rawtime);
Mon Jul 9 13:17:03 2012 //printf("%s", asctime(gmtime(&rawtime)));
2012year 7month 9day 13:17:3 //cout<<(ptm->tm_year + 1900)<<"year "<<(ptm->tm_mon + 1)<<"month "<<(ptm->tm_mday)<<"day "<<(ptm 28 ->tm_hour)<<":"<<(ptm->tm_min) <<":"<<(ptm->tm_sec)<<endl;
3.
結果 輸出 UTC 標准時間 12:49 //時間協調時間
********************
關於時間 定義的 struct tm的介紹:
struct tm
The structure contains nine members of type int, which are (in any order):
|
|
struct tm
{
int tm_sec; /*秒,正常范圍0-59, 但允許至61*/
int tm_min; /*分鍾,0-59*/
int tm_hour; /*小時, 0-23*/
int tm_mday; /*日,即一個月中的第幾天,1-31*/
int tm_mon; /*月, 從一月算起,0-11*/ 1+p->tm_mon;
int tm_year; /*年, 從1900至今已經多少年*/ 1900+ p->tm_year;
int tm_wday; /*星期,一周中的第幾天, 從星期日算起,0-6*/
int tm_yday; /*從今年1月1日到目前的天數,范圍0-365*/
int tm_isdst; /*日光節約時間的旗標*/
};
需要特別注意的是,年份是從1900年起至今多少年,而不是直接存儲如2011年,月份從0開始的,0表示一月,星期也是從0開始的, 0表示星期日,1表示星期一。
The meaning of each is:
Member | Meaning | Range |
---|---|---|
tm_sec | seconds after the minute | 0-61* |
tm_min | minutes after the hour | 0-59 |
tm_hour | hours since midnight | 0-23 |
tm_mday | day of the month | 1-31 |
tm_mon | months since January | 0-11: real month = tm_mon + 1 |
tm_year | years since 1900 | 1900+tm_year |
tm_wday | days since Sunday | 0-6 |
tm_yday | days since January 1 | 0-365 |
tm_isdst | Daylight Saving Time flag |
* tm_sec is generally 0-59. Extra range to accommodate for leap seconds in certain systems.