巧用C的Time函数进行时间转换

我们经常要遇到时间处理的问题,比如要开发一个schedule的功能,或根据修改时间来过滤文件等。windows API提供了Get*Time()系列函数用于获取当前时间,但是没有提供进行时间转换的,比如我们要得到距离当前时间2年4个月5天的时间,我们就得自己去计算了。但是这里有个问题,如果被减的天数大于当前月份的天数,那么天数就会变成负值。为了解决这个问题,我们就根据不同月份的天数来计算偏移,同时做月和年的变化。不过这种方法很麻烦,因为每个月天数是不同的还需要考虑闰年和平年的问题。其实C的Time系列函数可以很好的解决这个问题,

1. 首先用TM结构进行需要的时间偏移

2. 然后利用mktime这个函数将TM结构转换到从1900.1.1开始的秒数值

3. 再利用localtime 把秒数转换成TM结构

示例代码如下:

ExpandedBlockStart.gif 代码
#include  " stdafx.h "
#include 
< Windows.h >
#include 
< time.h >
#include 
< iostream >
using   namespace  std;

void  OffsetDateTime( const   struct  tm *  inST,  struct  tm *  outST,
                    
int  dYears,  int  dMonths,  int  dDays, 
                    
int  dHours,  int  dMinutes,  int  dSeconds)
{
    
if  (inST  !=  NULL  &&  outST  !=  NULL)
    {
          
//  偏移当前时间 
        outST -> tm_year  =  inST -> tm_year  -  dYears;
        outST
-> tm_mon   =  inST -> tm_mon   -  dMonths;
        outST
-> tm_mday  =  inST -> tm_mday  -  dDays;
        outST
-> tm_hour  =  inST -> tm_hour  -  dHours;
        outST
-> tm_min   =  inST -> tm_min   -  dMinutes;
        outST
-> tm_sec   =  inST -> tm_sec   -  dSeconds;
        
        
//  转换到从1900.1.1开始的总秒数
        time_t newRawTime  =  mktime(outST);
        
        
//  将秒数转换成时间结构体
        outST  =  localtime( & newRawTime);
    }
}


int  _tmain( int  argc, _TCHAR *  argv[])
{
    time_t rawtime;
    
struct  tm  *  st;
    
//  获取本地当前时间
    time( & rawtime);
    st 
=  localtime( & rawtime);
    cout 
<<  st -> tm_year  <<   " - "   <<  st -> tm_mon  <<   " - "   <<  st -> tm_mday  <<  endl;
    
    
//  计算时间偏移
     struct  tm outst;
    OffsetDateTime(st, 
& outst,  2 3 20 0 0 0 );
    time_t newTime 
=  mktime( & outst);

    cout 
<<  outst.tm_year  <<   " - "   <<  outst.tm_mon  <<   " - "   <<  outst.tm_mday  <<  endl;
    cout 
<<   " rawTime:  "   <<  rawtime  <<  endl  <<   " newTime : "   <<  newTime  <<  endl;

    
return   0 ;
}

 

 

 

 

转载于:https://www.cnblogs.com/moonz-wu/archive/2010/01/16/1649545.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值