两日期时间相差年月日时分秒的计算

这几天做一个c++写的插件用到两日期时间相减的差值显示为年月日时分秒,所以在网上找了一个函数使用,现共享一下代码:

#include <iostream>
#include <ctime>
#include <iomanip>
#include<string>

using namespace std;

int main()
{
    struct tm t1, t2;

    int rsjdw = 0;
    int rsjlength = 1;

    string sTime = "2309071509";
    string eTime = "2409081400";

    cout << "开始时间:" << sTime << endl;
    cout << "结束时间:" << eTime << endl;

    int tsyesr = stof("20" + sTime.substr(0, 2));
    int tsmon = stof(sTime.substr(2, 2));
    int tsday = stof(sTime.substr(4, 2));
    int tshour = stof(sTime.substr(6, 2));
    int tsmin = stof(sTime.substr(8, 2));

    int teyesr = stof("20" + eTime.substr(0, 2));
    int temon = stof(eTime.substr(2, 2));
    int teday = stof(eTime.substr(4, 2));
    int tehour = stof(eTime.substr(6, 2));
    int temin = stof(eTime.substr(8, 2));

    //时间节点1--2019年2月25日6时10分10秒
    t1.tm_sec = 0;
    t1.tm_min = tsmin;
    t1.tm_hour = tshour;
    t1.tm_mday = tsday;
    t1.tm_mon = tsmon;
    t1.tm_year = tsyesr - 1900;
    //时间节点2--2019年2月26日16时30分30秒
    t2.tm_sec = 0;
    t2.tm_min = temin;
    t2.tm_hour = tehour;
    t2.tm_mday = teday;
    t2.tm_mon = temon;
    t2.tm_year = teyesr - 1900;

    // 基于当前系统的当前日期/时间
    time_t now1 = mktime(&t1);
    time_t now2 = mktime(&t2);


    time_t now3;
    now3 = difftime(now2, now1);

    cout << "基于当前系统时间差值:" << now3 << "秒" << endl;
 

    // 如何使用 gmtime  警告 排除:添加  _CRT_SECURE_NO_WARNINGS
    tm * ltm = gmtime(&now3);

    // 输出 tm 结构的各个组成部分
    cout << "时间差值为";
    cout << ltm->tm_year - 70 << "年";
    cout << ltm->tm_mon << "月";
    cout << ltm->tm_mday - 1 << "日";
    cout << ltm->tm_hour << "时";
    cout << ltm->tm_min << "分";
    cout << ltm->tm_sec << "秒" << endl;
 


    return 0;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值