【C++】Linux下计算特定日期与纪元日期差值(秒)
0x00 前言
文章中的文字可能存在语法错误以及标点错误,请谅解;
如果在文章中发现代码错误或其它问题请告知,感谢!
0x01 代码实现
#include<iostream>
#include <chrono>
using namespace std;
struct MarkTime {
uint32_t year;
uint32_t month;
uint32_t day;
uint32_t hour;
uint32_t minute;
uint32_t second;
};
int main(){
auto get_current_seconds = []{
auto sys_clock = std::chrono::time_point_cast<std::chrono::seconds>(std::chrono::system_clock::now());
auto seconds = std::chrono::duration_cast<std::chrono::seconds>(sys_clock.time_since_epoch());
return seconds.count();
};
auto get_mark_time_seconds = [] (MarkTime time) {
std::tm mark_time = { 0};
mark_time.tm_year = time.year - 1900;
mark_time.tm_mon = time.month - 1;
mark_time.tm_mday = time.day;
mark_time.tm_hour = time.hour - 1;
mark_time.tm_min = time.minute;
mark_time.tm_sec = time.second;
auto tp = std::chrono::system_clock::from_time_t(std::mktime(&mark_time));
auto converted_mark_time = std::chrono::time_point_cast<std::chrono::seconds>(tp);
auto seconds = std::chrono::duration_cast<std::chrono::seconds>(converted_mark_time.time_since_epoch());
std::chrono::time_point<std::chrono::system_clock> stampTime(seconds);
std::time_t tmStampTime = std::chrono::system_clock::to_time_t(stampTime);
std::cout << "setting time: " << std::ctime(&tmStampTime) << std::endl; //设置时间
return seconds.count();
};
MarkTime SettingMarkTime = { 2021, 10, 31, 1, 1, 1}; //设置的年月日时分
auto epoch_time = std::chrono::system_clock::to_time_t(std::chrono::time_point<std::chrono::system_clock>{ });
std::cout << "epoch: " << std::ctime(&epoch_time) << std::endl; //纪元时间
auto today_time = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now());
std::cout << "today: " << std::ctime(&today_time) << std::endl; //系统当前时间
auto mark_time = get_mark_time_seconds(SettingMarkTime);
std::cout << "settint time to epoch: " << mark_time << "seconds" << std::endl; //设置时间距纪元时间(秒)
auto system_time = get_current_seconds(); //系统当前时间距纪元时间(秒)
std::cout << "today to epoch: " << system_time << "seconds" << std::endl;
return 0;
}
运行结果:
以上。
还没有评论,来说两句吧...