这几天做一个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;
}