如何让两个时间相减得到相应的差值(可得到相差的时分秒,年月日)

有时候我们需要知道某一个时间差具体是多少,比如:  2012-7-9 1:18:07  和 2012-7-11 3:25:04相差了多少时间,那么怎么解决这个问题呢?
在C++ Builder里面有这样一个专门处理时间差的函数库,里面有可以计算年差,月差,周差,日差,时差,分差,秒差的函数,函数如下所示:
YearsBetween  (const System::TDateTime ANow, const System::TDateTime AThen);
MonthsBetween (const System::TDateTime ANow, const System::TDateTime AThen);
WeeksBetween (const System::TDateTime ANow, const System::TDateTime AThen);
DaysBetween (const System::TDateTime ANow, const System::TDateTime AThen);
HoursBetween (const System::TDateTime ANow, const System::TDateTime AThen);
MinutesBetween (const System::TDateTime ANow, const System::TDateTime AThen);
SecondsBetween (const System::TDateTime ANow, const System::TDateTime AThen);
MilliSecondsBetween (const System::TDateTime ANow, const System::TDateTime AThen);


以上函数都包含在DateUtils.hpp中,使用的时候需要添加:#include <DateUtils.hpp>
举例:
void __fastcall TForm1::Button4Click(TObject *Sender)
{
        AnsiString stime,etime;
        int n,m;

        stime="2008-12-9 1:18:07";
        etime="2008-12-9 3:25:04";
        TDateTime t1 = StrToDateTime(stime);
        TDateTime t2 = StrToDateTime(etime);
        m=MinutesBetween(t1,t2);
        n=DaysBetween(t1,t2);
ShowMessage(m);
ShowMessage(n);
        //其余的差可以以此类推
  //記得include DateUtils.hpp
}
当然,还有一种方法就是计算绝对值差,如下所例:
int n,m;
        stime="2008-12-9 1:18:07";
        etime="2008-12-9 3:25:04";
        n=abs(24*60*(StrToDateTime(stime)-StrToDateTime(etime)));
        ShowMessage(n);
这得到的是分差,如果想要得到秒差,则:
n=abs(24*60*60(StrToDateTime(stime)-StrToDateTime(etime)));
其余的类推(貌似还没有找到算年差的方法)

小结:其实最好的方法还是使用第一种方式,c++ builder里面有这样的函数库,只需要在编译的时候将其包含进去就可以了,希望以后能够用到!

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值