1. 程式人生 > >C++時間與字符串轉換

C++時間與字符串轉換

utc 不用 字符串 函數 參數形式 minute art timezone 時區

轉自:http://blog.csdn.net/educast/article/details/17239735

1、常用的時間存儲方式

  • 1)time_t類型,這本質上是一個長整數,表示從1970-01-01 00:00:00到目前計時時間的秒數,如果需要更精確一點的,可以使用timeval精確到毫秒。
  • 2)tm結構,這本質上是一個結構體,裏面包含了各時間字段
 1 struct tm {  
 2         int tm_sec;     /* seconds after the minute - [0,59] */  
 3         int tm_min;     /* minutes after the hour - [0,59] 
*/ 4 int tm_hour; /* hours since midnight - [0,23] */ 5 int tm_mday; /* day of the month - [1,31] */ 6 int tm_mon; /* months since January - [0,11] */ 7 int tm_year; /* years since 1900 */ 8 int tm_wday; /* days since Sunday - [0,6] */ 9 int
tm_yday; /* days since January 1 - [0,365] */ 10 int tm_isdst; /* daylight savings time flag */ 11 };

其中tm_year表示從1900年到目前計時時間間隔多少年,如果是手動設置值的話,tm_isdst通常取值-1。

2、常用的時間函數

1 time_t time(time_t *t); //取得從1970年1月1日至今的秒數  
2 char *asctime(const struct tm *tm); //將結構中的信息轉換為真實世界的時間,以字符串的形式顯示  
3 char *ctime(const time_t *timep); //將timep轉換為真是世界的時間,以字符串顯示,它和asctime不同就在於傳入的參數形式不一樣 4 struct tm *gmtime(const time_t *timep); //將time_t表示的時間轉換為沒有經過時區轉換的UTC時間,是一個struct tm結構指針 5 struct tm *localtime(const time_t *timep); //和gmtime類似,但是它是經過時區轉換的時間。 6 time_t mktime(struct tm *tm); //將struct tm 結構的時間轉換為從1970年至今的秒數 7 .int gettimeofday(struct timeval *tv, struct timezone *tz); //返回當前距離1970年的秒數和微妙數,後面的tz是時區,一般不用 8 double difftime(time_t time1, time_t time2); //返回兩個時間相差的秒數

3、時間與字符串的轉換

需要包含的頭文件如下 :

1 #include <iostream>  
2 #include <time.h>  
3 #include <stdlib.h>  
4 #include <string.h>  

1)unix/windows下時間轉字符串參考代碼

 1 time_t t;  //秒時間  
 2 tm* local; //本地時間   
 3 tm* gmt;   //格林威治時間  
 4 char buf[128]= {0};    
 5 
 6 t = time(NULL); //獲取目前秒時間  
 7 local = localtime(&t); //轉為本地時間  
 8 strftime(buf, 64, "%Y-%m-%d %H:%M:%S", local);  
 9 std::cout << buf << std::endl;  
10   
11 gmt = gmtime(&t);//轉為格林威治時間  
12 strftime(buf, 64, "%Y-%m-%d %H:%M:%S", gmt);  
13 std::cout << buf << std::endl;  

2)unix字符串轉時間參考代碼

 1 tm tm_;  
 2 time_t t_;  
 3 char buf[128]= {0};  
 4   
 5 strcpy(buf, "2012-01-01 14:00:00");  
 6 strptime(buf, "%Y-%m-%d %H:%M:%S", &tm_); //將字符串轉換為tm時間  
 7 tm_.tm_isdst = -1;  
 8 t_  = mktime(&tm_); //將tm時間轉換為秒時間  
 9 t_ += 3600;  //秒數加3600  
10  
11 tm_ = *localtime(&t_);//輸出時間  
12 strftime(buf, 64, "%Y-%m-%d %H:%M:%S", &tm_);  
13 std::cout << buf << std::endl;  

3)由於windows下沒有strptime函數,所以可以使用scanf來格式化

 1 time_t StringToDatetime(char *str)  
 2 {  
 3     tm tm_;  
 4     int year, month, day, hour, minute,second;  
 5     sscanf(str,"%d-%d-%d %d:%d:%d", &year, &month, &day, &hour, &minute, &second);  
 6     tm_.tm_year  = year-1900;  
 7     tm_.tm_mon   = month-1;  
 8     tm_.tm_mday  = day;  
 9     tm_.tm_hour  = hour;  
10     tm_.tm_min   = minute;  
11     tm_.tm_sec   = second;  
12     tm_.tm_isdst = 0;  
13   
14     time_t t_ = mktime(&tm_); //已經減了8個時區  
15     return t_; //秒時間  
16 }  

C++時間與字符串轉換