您的位置:首页技术文章
文章详情页

UNIX环境下的日期程序

【字号: 日期:2024-06-06 16:06:29浏览:73作者:猪猪

前段时间做了一个计费程序,其中涉及到有关日期与时间的计算,如求某日某时的前(或后)一段时间是什么时候,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,chard_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] = '' ;

tb.tm_year = atoi( s1 );

strncpy( s1, s+4, 2 );

s1[2] = '' ;

tb.tm_mon = atoi( s1 );

strncpy( s1, s+6, 2 );

s1[2] = '' ;

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] = '' ;

tb.tm_hour = atoi( s1 );

strncpy( s1, s+10, 2 );

s1[2] = '' ;

tb.tm_min = atoi( s1 );

strncpy( s1, s+12, 2 );

s1[2] = '' ;

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 /

该函数不仅可求出某个时间前(后)一段时长的日期与时间,而且可得出这个日期是星期几,给程序设计带来不少便利,也方便了费用的计算与核实,读者可直接调用该函数。

标签: Unix系统
相关文章: