C 日期和時(shí)間函數(shù)

2018-05-19 17:46 更新

學(xué)習(xí)C - C日期和時(shí)間函數(shù)

time.h標(biāo)頭聲明產(chǎn)生時(shí)間和日期的函數(shù)。

獲取時(shí)間值

返回時(shí)間值的最簡(jiǎn)單的函數(shù)具有以下原型:

clock_t clock(void);

這個(gè)函數(shù)返回一些參考點(diǎn)后的處理器時(shí)間。

在程序中的某些進(jìn)程的開始和結(jié)束處,調(diào)用clock()函數(shù)。

返回值的類型為clock_t,它是在time.h中定義的整數(shù)類型。

clock()函數(shù)返回的值以時(shí)鐘刻度來(lái)度量。

要將此值轉(zhuǎn)換為秒,請(qǐng)將其除以由time.h中定義的宏CLOCKS_PER_SEC生成的值。

如果發(fā)生錯(cuò)誤,clock()函數(shù)返回-1。

time()函數(shù)返回日歷時(shí)間作為類型為time_t的值。

日歷時(shí)間是當(dāng)前時(shí)間,通常以特定日期的固定時(shí)間為單位,以秒為單位。

固定的時(shí)間和日期通常是1970年1月1日00:00:00 GMT,這是時(shí)間值的定義的典型。

time()函數(shù)的原型是:

time_t time(time_t *timer);

如果參數(shù)不為NULL,則當(dāng)前日歷時(shí)間也存儲(chǔ)在定時(shí)器中。

類型time_t在頭文件中定義,通常等同于long類型。

要計(jì)算time()返回的兩個(gè)連續(xù)time_t值之間的經(jīng)過(guò)時(shí)間(秒),可以使用具有此原型的difftime()函數(shù):

double difftime(time_t T2, time_t T1);

該函數(shù)將以秒為單位的T2 - T1值返回double類型的值。

該值是在產(chǎn)生time_t值T1和T2的兩個(gè)time()函數(shù)調(diào)用之間經(jīng)過(guò)的時(shí)間。


例子


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

int main(void) { 
  time_t calendar_start = time(NULL);         // Initial calendar time 
  clock_t cpu_start = clock();                // Initial processor time 
  int count = 0;                              // Count of number of loops 
  const long long iterations = 1000000000LL;  // Loop iterations 
  char answer = "y"; 
  double x = 0.0; 
  printf("Initial clock time = %lld Initial calendar time = %lld\n", 
            (long long)cpu_start, (long long)calendar_start); 
  while(tolower(answer) == "y") { 
    for(long long i = 0LL ; i < iterations ; ++i) 
      x = sqrt(3.14159265); 
  
    printf("%lld square roots completed.\n", iterations*(++count)); 
    printf("Do you want to run some more(y or n)? \n"); 
    scanf("\n%c", &answer, sizeof(answer)); 
  } 
  
  clock_t cpu_end = clock();                  // Final cpu time 
  time_t calendar_end = time(NULL);           // Final calendar time 
  
  printf("Final clock time = %lld Final calendar time = %lld\n", 
     (long long)cpu_end, (long long)calendar_end); 
  printf("CPU time for %lld iterations is %.2lf seconds\n", 
     count*iterations, ((double)(cpu_end-cpu_start))/CLOCKS_PER_SEC); 
  printf("Elapsed calendar time to execute the program is %8.2lf seconds.\n", 
     difftime(calendar_end, calendar_start)); 
  return 0; 
} 

上面的代碼生成以下結(jié)果。


獲取日期

要將今天的日期作為字符串,請(qǐng)使用具有此原型的函數(shù)ctime():

char *ctime(const time_t *timer);

該函數(shù)接受一個(gè)指向time_t變量的指針,作為包含由time()函數(shù)返回的日歷時(shí)間值的參數(shù)。

它返回一個(gè)指向包含日期,日期,時(shí)間和年份的26個(gè)字符的字符串的指針,它由換行符'\ 0'終止。

返回的典型字符串可能如下所示:

"Mon Aug 21 11:45:56 2015\n\0" 

ctime()函數(shù)不知道分配用于存儲(chǔ)結(jié)果的字符串長(zhǎng)度。

有一個(gè)可選的更安全的版本的功能有這個(gè)原型:

errno_t ctime_s(char * str, rsize_t size, const time_t *timer);

您可以使用ctime_s()函數(shù),如下所示:

char time_str[30] = {"\0"}; 
time_t calendar = time(NULL); 
if(!ctime_s(time_str, sizeof(time_str), &calendar)) 
   printf_s("%s", time_str); 
else 
   fprintf_s(stderr, "Error converting time_t value\n"); 
   

我們可以通過(guò)使用localtime()函數(shù)從日歷時(shí)間值獲取時(shí)間和日期的各個(gè)組件。這有原型:

struct tm *localtime(const time_t *timer);

此函數(shù)接受一個(gè)指向time_t值的指針,并返回一個(gè)指向tm類型的指針,該結(jié)構(gòu)在time.h中定義。

如果定時(shí)器無(wú)法轉(zhuǎn)換,則返回NULL。

可選版本有原型:

struct tm *localtime_s(const time_t * restrict timer, 
                            struct tm * restrict result); 

兩個(gè)參數(shù)必須為non_NULL。

該結(jié)構(gòu)至少包含下表中列出的成員。

成員描述
tm_sec秒(0到60)在24小時(shí)制的分鐘后。該值對(duì)于閏秒支持達(dá)到60。
tm_min24小時(shí)制的小時(shí)分鐘后(0到59)
tm_hour24小時(shí)制的小時(shí)(0到23)
tm_mday一月中的第幾天(1到31)
tm_mon月份(0至11)
tm_year年份(本年減去1900年)
tm_wday一周的第幾天(星期日為0;星期六為6)
tm_yday一年中的第幾天(0到365)
tm_isdst夏令時(shí)標(biāo)志。正為夏令時(shí)間,0不為夏令時(shí),負(fù)為不知道。

所有的成員都是int類型。

這是一個(gè)代碼片段,將從tm結(jié)構(gòu)的成員輸出日期和日期:

time_t calendar = time(NULL);                 // Current calendar time 
struct tm time_data; 
const char *days[] =   {"Sunday",   "Monday", "Tuesday", "Wednesday", 
                        "Thursday", "Friday", "Saturday"              }; 
const char *months[] = {"January", "February", "March", 
                        "April",    "May",     "June", 
                        "July",    "August",   "September", 
                        "October", "November", "December"  }; 

if(localtime_s(&calendar, &time_data)) 
  printf_s("Today is %s %s %d %d\n", 
                    days[time_data.tm_wday], months[time_data.tm_mon], 
                    time_data.tm_mday,       time_data.tm_year+1900); 

asctime()及其可選的更安全的伙伴asctime_s()生成一個(gè)tm結(jié)構(gòu)的字符串表示形式。

它們的原型是:

  
char *asctime(const struct tm *time_data); 
errno_t asctime_s(char *str, rsize_t size, const struct tm *time_data); 

asctime_s()將字符串存儲(chǔ)在str中,它必須是至少有26個(gè)元素的數(shù)組; size是str中元素的數(shù)量。

成功時(shí),該函數(shù)返回0,失敗時(shí)返回非零整數(shù)。

該函數(shù)適用??于年均1000到9999的tm結(jié)構(gòu)。

結(jié)果的字符串與ctime()生成的字符串格式相同。


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

int main(void) 
{ 
  const char *day[7] = { 
                   "Sunday"  , "Monday", "Tuesday", "Wednesday", 
                   "Thursday", "Friday", "Saturday" 
                       }; 
  const char *month[12] = { 
                     "January",   "February", "March",    "April", 
                     "May",       "June",     "July",     "August", 
                     "September", "October",  "November", "December" 
                          }; 
  const char *suffix[] = { "st", "nd", "rd", "th" }; 
  enum sufindex { st, nd, rd, th } sufsel = th;       // Suffix selector 
  
  struct tm ourT;                                     // The time structure 
  time_t tVal = time(NULL);                           // Calendar time 
  
  if(!localtime_s(&tVal, &ourT))                      // Populate time structure 
  { 
    fprintf(stderr, "Failed to populate tm struct.\n"); 
    return -1; 
  } 
  switch(ourT.tm_mday) 
  { 
    case 1: case 21: case 31: 
      sufsel= st; 
      break; 
    case 2: case 22: 
      sufsel= nd; 
      break; 
    case 3: case 23: 
      sufsel= rd; 
      break; 
    default: 
      sufsel= th; 
      break; 
  } 
  
  printf("Today is %s the %d%s %s %d. ", 
      day[ourT.tm_wday], 
      ourT.tm_mday, 
      suffix[sufsel], 
      month[ourT.tm_mon], 
      1900 + ourT.tm_year); 
  printf("The time is %d : %d : %d.\n", 
      ourT.tm_hour, ourT.tm_min, ourT.tm_sec ); 
  return 0; 
}

上面的代碼生成以下結(jié)果。

獲取日期的星期幾

您可以使用mktime()函數(shù)確定給定日期的星期幾。

該函數(shù)具有原型:

time_t mktime(struct tm *ptime);

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

int main(void) 
{ 
  const char *day[7] = { 
                   "Sunday"  , "Monday", "Tuesday", "Wednesday", 
                   "Thursday", "Friday", "Saturday" 
                       }; 
  const char *month[12] = { 
                     "January",   "February", "March",    "April", 
                     "May",       "June",     "July",     "August", 
                     "September", "October",  "November", "December" 
                          }; 
  const char *suffix[] = { "st", "nd", "rd", "th" }; 
  enum sufindex { st, nd, rd, th } sufsel = th;  // Suffix selector 
  
  struct tm birthday = {0};                      // A birthday time structure 
  char name[30] = {"C"}; 
  
  printf("Enter the birthday as day month year integers separated by spaces." 
             "\ne.g. Enter 1st February 1985 as 1 2 1985 : "); 
  scanf(" %d %d %d", &birthday.tm_mday, &birthday.tm_mon, &birthday.tm_year); 
  
  birthday.tm_mon -= 1;                          // Month zero-based 
  birthday.tm_year -= 1900;                      // Year relative to 1900 
  
  if(mktime(&birthday) == - 1) 
  { 
    fprintf_s(stderr, "Operation failed.\n"); 
    return -1; 
  } 
  
  switch(birthday.tm_mday) 
  { 
    case 1: case 21: case 31: 
      sufsel= st; 
      break; 
    case 2: case 22: 
      sufsel= nd; 
      break; 
    case 3: case 23: 
      sufsel= rd; 
      break; 
    default: 
      sufsel= th; 
      break; 
  } 
  printf("born on the %d%s %s %d, which was a %s.\n", 
                 birthday.tm_mday, suffix[sufsel], month[birthday.tm_mon], 
                            1900 + birthday.tm_year, day[birthday.tm_wday]); 
  return 0; 
} 

上面的代碼生成以下結(jié)果。

以上內(nèi)容是否對(duì)您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號(hào)
微信公眾號(hào)

編程獅公眾號(hào)