C/C++中的日期和時間

本文將主要介紹在C/C++中時間和日期的使用方法.

“時間”和“日期”的概念,主要有以下幾個:

Coordinated Universal Time(UTC):協調世界時,又稱爲世界標準時間,也就是大家所熟知的格林威治標準時間(Greenwich Mean Time,GMT)。比如,中國內地的時間與UTC的時差爲+8,也就是UTC+8。美國是UTC-5。

Calendar Time:日曆時間,是用“從一個標準時間點到此時的時間經過的秒數”來表示的時間。這個標準時間點對不同的編譯器來說會有所不同,但對一個編譯系統來說,這個標準時間點是不變的,該編譯系統中的時間對應的日曆時間都通過該標準時間點來衡量,所以可以說日曆時間是“相對時間”,但是無論你在哪一個時區,在同一時刻對同一個標準時間點來說,日曆時間都是一樣的。

epoch:時間點。時間點在標準C/C++中是一個整數,它用此時的時間和標準時間點相差的秒數(即日曆時間)來表示。

clock tick:時鐘計時單元(而不把它叫做時鐘滴答次數),一個時鐘計時單元的時間長短是由CPU控制的。一個clock tick不是CPU的一個時鐘週期,而是C/C++的一個基本計時單位。

我們可以使用ANSI標準庫中的time.h頭文件。這個頭文件中定義的時間和日期所使用的方法,無論是在結構定義,還是命名,都具有明顯的C語言風格。下面,將說明在C/C++中怎樣使用日期的時間功能。

2. 計時

C/C++中的計時函數是clock(),而與其相關的數據類型是clock_t。在MSDN中,查得對clock函數定義如下:

clock_t clock( void );

這個函數返回從“開啓這個程序進程”到“程序中調用clock()函數”時之間的CPU時鐘計時單元(clock tick)數,在MSDN中稱之爲掛鐘時間(wal-clock)。其中clock_t是用來保存時間的數據類型,在time.h文件中,我們可以找到對它的定義:

#ifndef _CLOCK_T_DEFINED
typedef long clock_t;
#define _CLOCK_T_DEFINED
#endif

很明顯,clock_t是一個長整形數。在time.h文件中,還定義了一個常量CLOCKS_PER_SEC,它用來表示一秒鐘會有多少個時鐘計時單元,其定義如下:

#define CLOCKS_PER_SEC ((clock_t)1000)

可以看到每過千分之一秒(1毫秒),調用clock()函數返回的值就加1。下面舉個例子,你可以使用公式clock()/CLOCKS_PER_SEC來計算一個進程自身的運行時間:

void elapsed_time()
{
printf("Elapsed time:%u secs./n",clock()/CLOCKS_PER_SEC);
}

當然,你也可以用clock函數來計算你的機器運行一個循環或者處理其它事件到底花了多少時間:

#include “stdio.h”
#include “stdlib.h”
#include “time.h”

int main( void )
{
long i = 10000000L;
clock_t start, finish;
double duration;
/* 測量一個事件持續的時間*/
printf( "Time to do %ld empty loops is ", i );
start = clock();
while( i-- )
finish = clock();
duration = (double)(finish - start) / CLOCKS_PER_SEC;
printf( "%f seconds/n", duration );
system("pause");
}

在筆者的機器上,運行結果如下:

Time to do 10000000 empty loops is 0.03000 seconds

上面我們看到時鐘計時單元的長度爲1毫秒,那麼計時的精度也爲1毫秒,那麼我們可不可以通過改變CLOCKS_PER_SEC的定義,通過把它定義的大一些,從而使計時精度更高呢?通過嘗試,你會發現這樣是不行的。在標準C/C++中,最小的計時單位是一毫秒。

3.與日期和時間相關的數據結構

在標準C/C++中,我們可通過tm結構來獲得日期和時間,tm結構在time.h中的定義如下:

#ifndef _TM_DEFINED
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代表一月) - 取值區間爲[0,11] */
int tm_year; /* 年份,其值等於實際年份減去1900 */
int tm_wday; /* 星期 – 取值區間爲[0,6],其中0代表星期天,1代表星期一,以此類推 */
int tm_yday; /* 從每年的1月1日開始的天數 – 取值區間爲[0,365],其中0代表1月1日,1代表1月2日,以此類推 */
int tm_isdst; /* 夏令時標識符,實行夏令時的時候,tm_isdst爲正。不實行夏令時的進候,tm_isdst爲0;不瞭解情況時,tm_isdst()爲負。*/
};
#define _TM_DEFINED
#endif

ANSI C標準稱使用tm結構的這種時間表示爲分解時間(broken-down time)。

而日曆時間(Calendar Time)是通過time_t數據類型來表示的,用time_t表示的時間(日曆時間)是從一個時間點(例如:1970年1月1日0時0分0秒)到此時的秒數。在time.h中,我們也可以看到time_t是一個長整型數:

#ifndef _TIME_T_DEFINED
typedef long time_t; /* 時間值 */
#define _TIME_T_DEFINED /* 避免重複定義 time_t */
#endif

大家可能會產生疑問:既然time_t實際上是長整型,到未來的某一天,從一個時間點(一般是1970年1月1日0時0分0秒)到那時的秒數(即日曆時間)超出了長整形所能表示的數的範圍怎麼辦?對time_t數據類型的值來說,它所表示的時間不能晚於2038年1月18日19時14分07秒。爲了能夠表示更久遠的時間,一些編譯器廠商引入了64位甚至更長的整形數來保存日曆時間。比如微軟在Visual C++中採用了__time64_t數據類型來保存日曆時間,並通過_time64()函數來獲得日曆時間(而不是通過使用32位字的time()函數),這樣就可以通過該數據類型保存3001年1月1日0時0分0秒(不包括該時間點)之前的時間。

在time.h頭文件中,我們還可以看到一些函數,它們都是以time_t爲參數類型或返回值類型的函數:

double difftime(time_t time1, time_t time0);
time_t mktime(struct tm * timeptr);
time_t time(time_t * timer);
char * asctime(const struct tm * timeptr);
char * ctime(const time_t *timer);

此外,time.h還提供了兩種不同的函數將日曆時間(一個用time_t表示的整數)轉換爲我們平時看到的把年月日時分秒分開顯示的時間格式tm:

struct tm * gmtime(const time_t *timer);
struct tm * localtime(const time_t * timer);

通過查閱MSDN,我們可以知道Microsoft C/C++ 7.0中時間點的值(time_t對象的值)是從1899年12月31日0時0分0秒到該時間點所經過的秒數,而其它各種版本的Microsoft C/C++和所有不同版本的Visual C++都是計算的從1970年1月1日0時0分0秒到該時間點所經過的秒數。

4.與日期和時間相關的函數及應用
在本節,我將向大家展示怎樣利用time.h中聲明的函數對時間進行操作。這些操作包括取當前時間、計算時間間隔、以不同的形式顯示時間等內容。

4.1 獲得日曆時間

我們可以通過time()函數來獲得日曆時間(Calendar Time),其原型爲:

time_t time(time_t * timer);

如果你已經聲明瞭參數timer,你可以從參數timer返回現在的日曆時間,同時也可以通過返回值返回現在的日曆時間,即從一個時間點(例如:1970年1月1日0時0分0秒)到現在此時的秒數。如果參數爲空(NUL),函數將只通過返回值返回現在的日曆時間,比如下面這個例子用來顯示當前的日曆時間:

#include "time.h"
#include "stdio.h"
int main(void)
{
struct tm *ptr;
time_t lt;
lt =time(NUL);
printf("The Calendar Time now is %d/n",lt);
return 0;
}

運行的結果與當時的時間有關,我當時運行的結果是:

The Calendar Time now is 1122707619

其中1122707619就是我運行程序時的日曆時間。即從1970年1月1日0時0分0秒到此時的秒數。

4.2 獲得日期和時間

這裏說的日期和時間就是我們平時所說的年、月、日、時、分、秒等信息。從第2節我們已經知道這些信息都保存在一個名爲tm的結構體中,那麼如何將一個日曆時間保存爲一個tm結構的對象呢?

其中可以使用的函數是gmtime()和localtime(),這兩個函數的原型爲:

struct tm * gmtime(const time_t *timer);
struct tm * localtime(const time_t * timer);

其中gmtime()函數是將日曆時間轉化爲世界標準時間(即格林尼治時間),並返回一個tm結構體來保存這個時間,而localtime()函數是將日曆時間轉化爲本地時間。比如現在用gmtime()函數獲得的世界標準時間是2005年7月30日7點18分20秒,那麼我用localtime()函數在中國地區獲得的本地時間會比世界標準時間晚8個小時,即2005年7月30日15點18分20秒。下面是個例子:

#include "time.h"
#include "stdio.h"
int main(void)
{
struct tm *local;
time_t t;
t=time(NUL);
local=localtime(&t);
printf("Local hour is: %d/n",local->tm_hour);
local=gmtime(&t);
printf("UTC hour is: %d/n",local->tm_hour);
return 0;
}

運行結果是:

Local hour is: 15
UTC hour is: 7

4.3 固定的時間格式

我們可以通過asctime()函數和ctime()函數將時間以固定的格式顯示出來,兩者的返回值都是char*型的字符串。返回的時間格式爲:

星期幾 月份 日期 時:分:秒 年/n/0
例如:Wed Jan 02 02:03:55 1980/n/0

其中/n是一個換行符,/0是一個空字符,表示字符串結束。下面是兩個函數的原型:

char * asctime(const struct tm * timeptr);
char * ctime(const time_t *timer);

其中asctime()函數是通過tm結構來生成具有固定格式的保存時間信息的字符串,而ctime()是通過日曆時間來生成時間字符串。這樣的話,asctime()函數只是把tm結構對象中的各個域填到時間字符串的相應位置就行了,而ctime()函數需要先參照本地的時間設置,把日曆時間轉化爲本地時間,然後再生成格式化後的字符串。在下面,如果t是一個非空的time_t變量的話,那麼:

printf(ctime(&t));

等價於:

struct tm *ptr;
ptr=localtime(&t);
printf(asctime(ptr));

那麼,下面這個程序的兩條printf語句輸出的結果就是不同的了(除非你將本地時區設爲世界標準時間所在的時區):

#include "time.h"
#include "stdio.h"
int main(void)
{
struct tm *ptr;
time_t lt;
lt =time(NUL);
ptr=gmtime(<);
printf(asctime(ptr));
printf(ctime(<));
return 0;
}

運行結果:

Sat Jul 30 08:43:03 2005
Sat Jul 30 16:43:03 2005

4.4 自定義時間格式

我們可以使用strftime()函數將時間格式化爲我們想要的格式。它的原型如下:

size_t strftime(
char *strDest,
size_t maxsize,
const char *format,
const struct tm *timeptr
);

我們可以根據format指向字符串中格式命令把timeptr中保存的時間信息放在strDest指向的字符串中,最多向strDest中存放maxsize個字符。該函數返回向strDest指向的字符串中放置的字符數。

函數strftime()的操作有些類似於sprintf():識別以百分號(%)開始的格式命令集合,格式化輸出結果放在一個字符串中。格式化命令說明串strDest中各種日期和時間信息的確切表示方法。格式串中的其他字符原樣放進串中。格式命令列在下面,它們是區分大小寫的。

%a 星期幾的簡寫
%A 星期幾的全稱
%b 月分的簡寫
%B 月份的全稱
%c 標準的日期的時間串
%C 年份的後兩位數字
%d 十進制表示的每月的第幾天
%D 月/天/年
%e 在兩字符域中,十進制表示的每月的第幾天
%F 年-月-日
%g 年份的後兩位數字,使用基於周的年
%G 年分,使用基於周的年
%h 簡寫的月份名
%H 24小時制的小時
%I 12小時制的小時
%j 十進制表示的每年的第幾天
%m 十進制表示的月份
%M 十時製表示的分鐘數
%n 新行符
%p 本地的AM或PM的等價顯示
%r 12小時的時間
%R 顯示小時和分鐘:hh:mm
%S 十進制的秒數
%t 水平製表符
%T 顯示時分秒:hh:mm:ss
%u 每週的第幾天,星期一爲第一天 (值從0到6,星期一爲0)
%U 第年的第幾周,把星期日做爲第一天(值從0到53)
%V 每年的第幾周,使用基於周的年
%w 十進制表示的星期幾(值從0到6,星期天爲0)
%W 每年的第幾周,把星期一做爲第一天(值從0到53)
%x 標準的日期串
%X 標準的時間串
%y 不帶世紀的十進制年份(值從0到99)
%Y 帶世紀部分的十進制年份
%z,%Z 時區名稱,如果不能得到時區名稱則返回空字符。
%% 百分號

如果想顯示現在是幾點了,並以12小時制顯示,就象下面這段程序:

#include “time.h”
#include “stdio.h”
int main(void)
{
struct tm *ptr;
time_t lt;
char str[80];
lt=time(NUL);
ptr=localtime(<);
strftime(str,100,"It is now %I %p",ptr);
printf(str);
return 0;
}

其運行結果爲:
It is now 4PM

而下面的程序則顯示當前的完整日期:

#include <stdio.h>
#include <time.h>

void main( void )
{
struct tm *newtime;
char tmpbuf[128];
time_t lt1;
time( <1 );
newtime=localtime(<1);
strftime( tmpbuf, 128, "Today is %A, day %d of %B in the year %Y./n", newtime);
printf(tmpbuf);
}

運行結果:

Today is Saturday, day 30 of July in the year 2005.

4.5 計算持續時間的長度

有時候在實際應用中要計算一個事件持續的時間長度,比如計算打字速度。在第1節計時部分中,我已經用clock函數舉了一個例子。Clock()函數可以精確到毫秒級。同時,我們也可以使用difftime()函數,但它只能精確到秒。該函數的定義如下:

double difftime(time_t time1, time_t time0);

雖然該函數返回的以秒計算的時間間隔是double類型的,但這並不說明該時間具有同double一樣的精確度,這是由它的參數覺得的(time_t是以秒爲單位計算的)。比如下面一段程序:

#include "time.h"
#include "stdio.h"
#include "stdlib.h"
int main(void)
{
time_t start,end;
start = time(NUL);
system("pause");
end = time(NUL);
printf("The pause used %f seconds./n",difftime(end,start));//<-
system("pause");
return 0;
}

運行結果爲:
請按任意鍵繼續. . .
The pause used 2.000000 seconds.
請按任意鍵繼續. . .

可以想像,暫停的時間並不那麼巧是整整2秒鐘。其實,你將上面程序的帶有“//<-”註釋的一行用下面的一行代碼替換:

printf("The pause used %f seconds./n",end-start);

其運行結果是一樣的。

4.6 分解時間轉化爲日曆時間

這裏說的分解時間就是以年、月、日、時、分、秒等分量保存的時間結構,在C/C++中是tm結構。我們可以使用mktime()函數將用tm結構表示的時間轉化爲日曆時間。其函數原型如下:

time_t mktime(struct tm * timeptr);

其返回值就是轉化後的日曆時間。這樣我們就可以先制定一個分解時間,然後對這個時間進行操作了,下面的例子可以計算出1997年7月1日是星期幾:

#include "time.h"
#include "stdio.h"
#include "stdlib.h"
int main(void)
{
struct tm t;
time_t t_of_day;
t.tm_year=1997-1900;
t.tm_mon=6;
t.tm_mday=1;
t.tm_hour=0;
t.tm_min=0;
t.tm_sec=1;
t.tm_isdst=0;
t_of_day=mktime(&t);
printf(ctime(&t_of_day));
return 0;
}

運行結果:

Tue Jul 01 00:00:01 1997

現在注意了,有了mktime()函數,是不是我們可以操作現在之前的任何時間呢?你可以通過這種辦法算出1945年8月15號是星期幾嗎?答案是否定的。因爲這個時間在1970年1月1日之前,所以在大多數編譯器中,這樣的程序雖然可以編譯通過,但運行時會異常終止。

5.總結

本文介紹了標準C/C++中的有關日期和時間的概念,並通過各種實例講述了這些函數和數據結構的使用方法。筆者認爲,和時間相關的一些概念是相當重要的,理解這些概念是理解各種時間格式的轉換的基礎,更是應用這些函數和數據結構的基礎。

6.附錄
1)日期類型轉換
a.Converting a time_t Value to a File Time
void TimetToFileTime( time_t t, LPFILETIME pft )
{
    LONGLONG ll = Int32x32To64(t, 10000000) + 116444736000000000;
    pft->dwLowDateTime = (DWORD) ll;
    pft->dwHighDateTime = ll >>32;
}
b. Converting a File Time to a time_t Value
void FileTimeToTimet(LPFILETIME pft,time_t& t)
{
     LONGLONG ll = pft->dwHighDateTime;
     ll <<= 32;
     ll  |= ft.dwLowDateTime;
     ll  -= 116444736000000000;
     t  = (time_t)(ll / 10000000);
}
c.FileTimeToSystemTime (API)
d.Converts a time value to a structure.
struct tm *gmtime( const time_t *timer )
e.
Converts the local time to a calendar value.
time_t mktime( struct tm *timeptr );
f.Converts a OLE DATE to a tm structure

 

static BOOL GetTmFromOleDate(DATE dtSrc, struct tm& tmDest)
{
// The legal range does not actually span year 0 to 9999.
    if (dtSrc > MAX_DATE || dtSrc < MIN_DATE) // about year 100 to about 9999
        return FALSE;
    
long nDays;             // Number of days since Dec. 30, 1899
    long nDaysAbsolute;     // Number of days since 1/1/0
    long nSecsInDay;        // Time in seconds since midnight
    long nMinutesInDay;     // Minutes in day

    
long n400Years;         // Number of 400 year increments since 1/1/0
    long n400Century;       // Century within 400 year block (0,1,2 or 3)
    long n4Years;           // Number of 4 year increments since 1/1/0
    long n4Day;             // Day within 4 year block
                            
//  (0 is 1/1/yr1, 1460 is 12/31/yr4)
    long n4Yr;              // Year within 4 year block (0,1,2 or 3)
    BOOL bLeap4 = TRUE;     // TRUE if 4 year block includes leap year

    
double dblDate = dtSrc; // tempory serial date

    
// If a valid date, then this conversion should not overflow
    nDays = (long)dblDate;

    
// Round to the second
    dblDate += ((dtSrc > 0.0? HALF_SECOND : -HALF_SECOND);

    nDaysAbsolute 
= (long)dblDate + 693959L// Add days from 1/1/0 to 12/30/1899

    dblDate 
= fabs(dblDate);
    nSecsInDay 
= (long)((dblDate - floor(dblDate)) * 86400.);

    
// Calculate the day of week (sun=1, mon=2)
    
//   -1 because 1/1/0 is Sat.  +1 because we want 1-based
    tmDest.tm_wday = (int)((nDaysAbsolute - 1% 7L+ 1;

    
// Leap years every 4 yrs except centuries not multiples of 400.
    n400Years = (long)(nDaysAbsolute / 146097L);

    
// Set nDaysAbsolute to day within 400-year block
    nDaysAbsolute %= 146097L;

    
// -1 because first century has extra day
    n400Century = (long)((nDaysAbsolute - 1/ 36524L);

    
// Non-leap century
    if (n400Century != 0)
    
{
        
// Set nDaysAbsolute to day within century
        nDaysAbsolute = (nDaysAbsolute - 1% 36524L;

        
// +1 because 1st 4 year increment has 1460 days
        n4Years = (long)((nDaysAbsolute + 1/ 1461L);

        
if (n4Years != 0)
            n4Day 
= (long)((nDaysAbsolute + 1% 1461L);
        
else
        
{
            bLeap4 
= FALSE;
            n4Day 
= (long)nDaysAbsolute;
        }

    }

    
else
    
{
        
// Leap century - not special case!
        n4Years = (long)(nDaysAbsolute / 1461L);
        n4Day 
= (long)(nDaysAbsolute % 1461L);
    }


    
if (bLeap4)
    
{
        
// -1 because first year has 366 days
        n4Yr = (n4Day - 1/ 365;

        
if (n4Yr != 0)
            n4Day 
= (n4Day - 1% 365;
    }

    
else
    
{
        n4Yr 
= n4Day / 365;
        n4Day 
%= 365;
    }


    
// n4Day is now 0-based day of year. Save 1-based day of year, year number
    tmDest.tm_yday = (int)n4Day + 1;
    tmDest.tm_year 
= n400Years * 400 + n400Century * 100 + n4Years * 4 + n4Yr;

    
// Handle leap year: before, on, and after Feb. 29.
    if (n4Yr == 0 && bLeap4)
    
{
        
// Leap Year
        if (n4Day == 59)
        
{
            
/* Feb. 29 */
            tmDest.tm_mon 
= 2;
            tmDest.tm_mday 
= 29;
            
goto DoTime;
        }


        
// Pretend it's not a leap year for month/day comp.
        if (n4Day >= 60)
            
--n4Day;
    }


    
// Make n4DaY a 1-based day of non-leap year and compute
    
//  month/day for everything but Feb. 29.
    ++n4Day;

    
// Month number always >= n/32, so save some loop time */
    for (tmDest.tm_mon = (n4Day >> 5+ 1;
        n4Day 
> _afxMonthDays[tmDest.tm_mon]; tmDest.tm_mon++);

    tmDest.tm_mday 
= (int)(n4Day - _afxMonthDays[tmDest.tm_mon-1]);

DoTime:
    
if (nSecsInDay == 0)
        tmDest.tm_hour 
= tmDest.tm_min = tmDest.tm_sec = 0;
    
else
    
{
        tmDest.tm_sec 
= (int)nSecsInDay % 60L;
        nMinutesInDay 
= nSecsInDay / 60L;
        tmDest.tm_min 
= (int)nMinutesInDay % 60;
        tmDest.tm_hour 
= (int)nMinutesInDay / 60;
    }


    tmDest.tm_wday
--;
    tmDest.tm_mon
--;
    tmDest.tm_year 
-= 1900;

    
return TRUE;
}

 

 

g.Converts a tm structure to a OLE Date

 

static BOOL GetDateFromTm(short wYear, short wMonth, DWORD wDay,
    DWORD wHour, DWORD wMinute, DWORD wSecond, DATE
& dtDest)
{
    
// Validate year and month (ignore day of week and milliseconds)
    if (wYear > 9999 || wMonth < 1 || wMonth > 12)
        
return FALSE;

    
//  Check for leap year and set the number of days in the month
    BOOL bLeapYear = ((wYear & 3== 0&&
        ((wYear 
% 100!= 0 || (wYear % 400== 0);

    
int nDaysInMonth =
        _afxMonthDays[wMonth] 
- _afxMonthDays[wMonth-1+
        ((bLeapYear 
&& wDay == 29 && wMonth == 2? 1 : 0);

    
// Finish validating the date
    if (wDay < 1 || wDay > (unsigned long)nDaysInMonth ||
        wHour 
> 23 || wMinute > 59 ||
        wSecond 
> 59)
    
{
        
return FALSE;
    }


    
// Cache the date in days and time in fractional days
    long nDate;
    
double dblTime;

    
//It is a valid date; make Jan 1, 1AD be 1
    nDate = wYear*365L + wYear/4 - wYear/100 + wYear/400 +
        _afxMonthDays[wMonth
-1+ wDay;

    
//  If leap year and it's before March, subtract 1:
    if (wMonth <= 2 && bLeapYear)
        
--nDate;

    
//  Offset so that 12/30/1899 is 0
    nDate -= 693959L;

    dblTime 
= (((long)wHour * 3600L+  // hrs in seconds
        ((long)wMinute * 60L+  // mins in seconds
        ((long)wSecond)) / 86400.;

    dtDest 
= (double) nDate + ((nDate >= 0? dblTime : -dblTime);

    
return TRUE;
}

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