1. 程式人生 > >介紹幾個C++程式中關於"時間"的函式

介紹幾個C++程式中關於"時間"的函式

時間,我們每天都在與之打交道。

程式的世界中更是,時間無處不在。

在你編寫程式的時候,很多時候需要獲取當前的時間,並且進行格式化輸出,所以心血來潮,就想著整理蒐集幾個關於“時間”的函式。

但是需要強調一點,本部落格裡所介紹的函式都是C++語言中的。

time函式
原型:

time_t time (time_t* timer);

作用:
Get the current calendar time as a value of type time_t.

The function returns this value, and if the argument is not a null pointer, it also sets this value to the object pointed by timer.

The value returned generally represents the number of seconds since 00:00 hours, Jan 1, 1970 UTC (i.e., the current unix timestamp).

這裡需要說明一下 什麼是時間戳?
Unix時間戳(Unix timestamp),或稱Unix時間(Unix time)、POSIX時間(POSIX time),是一種時間表示方式,定義為從格林威治時間1970年01月01日00時00分00秒(北京時間1970年01月01日08時00分00秒)起至現在的總秒數。Unix時間戳不僅被使用在Unix系統、類Unix系統中(比如Linux系統),也在許多其他作業系統中被廣泛採用。

使用:

#include <stdio.h>      /* printf */
#include <time.h>       /* time_t, struct tm, difftime, time, mktime */

int main ()
{
  time_t timer;
  struct tm y2k = {0};
  double seconds;

  y2k.tm_hour = 0;   y2k.tm_min = 0; y2k.tm_sec = 0;
  y2k.tm_year = 100; y2k.tm_mon = 0; y2k.tm_mday = 1;

  time
(&timer); /* get current time; same as: timer = time(NULL) */ seconds = difftime(timer,mktime(&y2k)); printf ("%.f seconds since January 1, 2000 in the current timezone", seconds); return 0; }

Although libraries may use a different representation of time: Portable programs should not use the value returned by this function directly, but always rely on calls to other elements of the standard library to translate them to portable types (such as localtime, gmtime or difftime).

localtime函式

struct tm * localtime (const time_t * timer);

作用:
Uses the value pointed by timer to fill a tm structure with the values that represent the corresponding time, expressed for the local timezone.

應用:

#include <stdio.h>      /* puts, printf */
#include <time.h>       /* time_t, struct tm, time, localtime */

int main ()
{
  time_t rawtime;
  struct tm * timeinfo;

  time (&rawtime);
  timeinfo = localtime (&rawtime);
  printf ("Current local time and date: %s", asctime(timeinfo));

  return 0;
}

gmtime函式
原型:

struct tm * gmtime (const time_t * timer);

作用:
Convert time_t to tm as UTC time
使用:

#include <stdio.h>      /* puts, printf */
#include <time.h>       /* time_t, struct tm, time, gmtime */

#define MST (-7)
#define UTC (0)
#define CCT (+8)

int main ()
{
  time_t rawtime;
  struct tm * ptm;

  time ( &rawtime );

  ptm = gmtime ( &rawtime );

  puts ("Current time around the World:");
  printf ("Phoenix, AZ (U.S.) :  %2d:%02d\n", (ptm->tm_hour+MST)%24, ptm->tm_min);
  printf ("Reykjavik (Iceland) : %2d:%02d\n", (ptm->tm_hour+UTC)%24, ptm->tm_min);
  printf ("Beijing (China) :     %2d:%02d\n", (ptm->tm_hour+CCT)%24, ptm->tm_min);

  return 0;
}

tm結構
在標準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()為負。*/

strftime函式
原型:

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

作用:
Format time as string

specifier                 Replaced by                          Example
%a               Abbreviated weekday name *                      Thu
%A                  Full weekday name *                       Thursday
%b                Abbreviated month name *                       Aug
%B                    Full month name *                        August
%c            Date and time representation *     Thu Aug 23 14:55:02 2001
%C       Year divided by 100 and truncated to integer (00-99)   20
%d         Day of the month, zero-padded (01-31)                23
%D           Short MM/DD/YY date, equivalent to %m/%d/%y     08/23/01
%e             Day of the month, space-padded ( 1-31)           23
%F          Short YYYY-MM-DD date, equivalent to %Y-%m-%d   2001-08-23
%g               Week-based year, last two digits (00-99)       01
%G                      Week-based year                        2001
%h                 Abbreviated month name * (same as %b)        Aug
%H                  Hour in 24h format (00-23)                  14
%I                   Hour in 12h format (01-12)                 02
%j                  Day of the year (001-366)                   235
%m                  Month as a decimal number (01-12)           08
%M                    Minute (00-59)                            55
%n                     New-line character                      ('\n')   
%p                        AM or PM designation                   PM
%r                         12-hour clock time *          02:55:02 pm
%R               24-hour HH:MM time, equivalent to %H:%M       14:55
%S                        Second (00-61)                          02
%t                       Horizontal-tab character             ('\t')    
%T  ISO 8601 time format (HH:MM:SS), equivalent to %H:%M:%S 14:55:02
%u      ISO 8601 weekday as number with Monday as 1 (1-7)       4
%U  Week number with the first Sunday as the first day of week one (00-53)  33
%V               ISO 8601 week number (00-53)                    34
%w        Weekday as a decimal number with Sunday as 0 (0-6)      4
%W  Week number with the first Monday as the first day of week one (00-53)  34
%x                  Date representation *                     08/23/01
%X                   Time representation *                    14:55:02
%y                   Year, last two digits (00-99)                01
%Y                   Year                                        2001
%z        ISO 8601 offset from UTC in timezone (1 minute=1, 1 hour=100)
If timezone cannot be determined, no characters +100
%Z              Timezone name or abbreviation *
          If timezone cannot be determined, no characters   CDT
%%                     A % sign                                      %
time_t tmBegin = 1351118531;    //2012-10-25 06:42:11
time_t tmEnd = 1351218731;      //2012-10-26 10:32:11
tm* ptmBegin = localtime(&tmBegin );
tm* ptmEnd = localtime(&tmEnd );//第二次呼叫會修改上次呼叫的tm結構體,若上次的資料未儲存則會丟失
//tm* ptm3 = gmtime(&tmEnd );       //效果同上條語句,也會重寫之前的資料
char ctmBegin1[26], ctmEnd[26];
strftime(ctmBegin, 26, "%Y%m%d%H%M%S", ptmBegin);   //這裡輸出的將是tmEnd的時間值
strftime(ctmEnd, 26, "%Y%m%d%H%M%S", ptmEnd);

/*MSDN中有相關說明:
Both the 32-bit and 64-bit versions ofgmtime, mktime, mkgmtime, and localtimeall&nbsp;use a single tm structure per thread for the conversion.&nbsp;Each call to one of these routines&nbsp;destroys the result of the previous call. 
*/

所以要記住,一旦呼叫了localtime函式,應該馬上取出tm結構中的內容

time_t tmBegin = 1351118531;        //2012-10-25 06:42:11
time_t tmEnd = 1351218731;      //2012-10-26 10:32:11
char ctmBegin1[26], ctmEnd[26];
tm* ptmBegin = localtime(&tmBegin );
strftime(ctmBegin, 26, "%Y%m%d%H%M%S", ptmBegin);
tm* ptmEnd = localtime(&tmEnd );    
strftime(ctmEnd, 26, "%Y%m%d%H%M%S", ptmEnd);
//tm* ptm3 = gmtime(&tmEnd );