[ 永遠的UNIX::UNIX技術資料的寶庫 ]   GB | BIG5

首頁 > 編程技術 > C/C++ > 正文
UNIX環境下的日期程序(求時間的函數)
本文出自:http://www.ccidnet.com/ 作者: 李斌兵 (2002-01-06 08:30:00)
前段時間做了一個計費程序,其中涉及到有關日期與時間的計算,如求某日某時的前
(或)一段時間是什時候,UNIX C系統本身並未提供此類函數,筆者經摸索,設
計了一個求時間的函數,現介紹給大家。

功能介紹與參數說明

該函數的主要功能是根據給定的日期時間及時長求出此前或(bill_long為負)的日
期時間及其星期。

參數說明如下:

s:為給定的日期時間,如2001年6月2日18點30分04秒為“20010602183004”;
  bill_long:給定的時間長度,單位為秒;
  d_str:求出的日期,如2001年6月2日為“20010602”;
  t_str:求出的時間,如18點28分06秒為“182806”;
  函數返回值為星期,如星期日為0,星期一至六分別對應1∼6。

實現代碼

該函數的具體實現代碼如下:

  int GetDateTime( char s,long int bill_long,chard_str, char t_str) {
   time_t timer,tim ;
   struct tm tb, tb1 ;
   int year_off = 1900 ;
   int mon_off = 1 ;
   char s1[20] ;
   if ( strlen( s )!=14 )
   return -1;
   strncpy( s1, s, 4 );
   s1[4] = '\0' ;
   tb.tm_year = atoi( s1 );
   strncpy( s1, s+4, 2 );
   s1[2] = '\0' ;
   tb.tm_mon = atoi( s1 );
   strncpy( s1, s+6, 2 );
   s1[2] = '\0' ;
   tb.tm_mday = atoi( s1 );
   if ( tb.tm_year==0 || tb.tm_mon==0 ||tb.tm_mday==0 )
   return -1;
   strncpy( s1, s+8, 2 );
   s1[2] = '\0' ;
   tb.tm_hour = atoi( s1 );
   strncpy( s1, s+10, 2 );
   s1[2] = '\0' ;
   tb.tm_min = atoi( s1 );
   strncpy( s1, s+12, 2 );
   s1[2] = '\0' ;
   tb.tm_sec = atoi( s1 );
   tb.tm_year -= year_off ;
   tb.tm_mon -= mon_off ;
   tb.tm_isdst = 0 ;
   tim=mktime( &tb ) ;
   tim=tim-bill_long;
   tb1=localtime(&tim);
   sprintf(d_str, "%#04d%#02d%#02d",1900+tb1->tm_year,tb1->tm_mon+1,tb1->tm_mday);
   sprintf(t_str, "%#02d%#02d%#02d",tb1->tm_hour, tb1->tm_min,tb1->tm_sec);
   return (tb1->tm_wday);
  } / end of GetDateTime /

該函數不僅可求出某個時間前()一段時長的日期與時間,而且可得出這個日期是星期幾,
給程序設計帶來不少便利,也方便了費用的計算與核實,讀者可直接調用該函數。
 
 
(http://www.fanqiang.com)
    進入【UNIX論壇

相關文章
 

★  樊強制作 歡迎分享  ★