【C++】Linux下计算特定日期与纪元日期差值(秒)

绝地灬酷狼 2022-09-16 15:19 266阅读 0赞

0x00 前言

文章中的文字可能存在语法错误以及标点错误,请谅解;

如果在文章中发现代码错误或其它问题请告知,感谢!

0x01 代码实现

  1. #include<iostream>
  2. #include <chrono>
  3. using namespace std;
  4. struct MarkTime {
  5. uint32_t year;
  6. uint32_t month;
  7. uint32_t day;
  8. uint32_t hour;
  9. uint32_t minute;
  10. uint32_t second;
  11. };
  12. int main(){
  13. auto get_current_seconds = []{
  14. auto sys_clock = std::chrono::time_point_cast<std::chrono::seconds>(std::chrono::system_clock::now());
  15. auto seconds = std::chrono::duration_cast<std::chrono::seconds>(sys_clock.time_since_epoch());
  16. return seconds.count();
  17. };
  18. auto get_mark_time_seconds = [] (MarkTime time) {
  19. std::tm mark_time = { 0};
  20. mark_time.tm_year = time.year - 1900;
  21. mark_time.tm_mon = time.month - 1;
  22. mark_time.tm_mday = time.day;
  23. mark_time.tm_hour = time.hour - 1;
  24. mark_time.tm_min = time.minute;
  25. mark_time.tm_sec = time.second;
  26. auto tp = std::chrono::system_clock::from_time_t(std::mktime(&mark_time));
  27. auto converted_mark_time = std::chrono::time_point_cast<std::chrono::seconds>(tp);
  28. auto seconds = std::chrono::duration_cast<std::chrono::seconds>(converted_mark_time.time_since_epoch());
  29. std::chrono::time_point<std::chrono::system_clock> stampTime(seconds);
  30. std::time_t tmStampTime = std::chrono::system_clock::to_time_t(stampTime);
  31. std::cout << "setting time: " << std::ctime(&tmStampTime) << std::endl; //设置时间
  32. return seconds.count();
  33. };
  34. MarkTime SettingMarkTime = { 2021, 10, 31, 1, 1, 1}; //设置的年月日时分
  35. auto epoch_time = std::chrono::system_clock::to_time_t(std::chrono::time_point<std::chrono::system_clock>{ });
  36. std::cout << "epoch: " << std::ctime(&epoch_time) << std::endl; //纪元时间
  37. auto today_time = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now());
  38. std::cout << "today: " << std::ctime(&today_time) << std::endl; //系统当前时间
  39. auto mark_time = get_mark_time_seconds(SettingMarkTime);
  40. std::cout << "settint time to epoch: " << mark_time << "seconds" << std::endl; //设置时间距纪元时间(秒)
  41. auto system_time = get_current_seconds(); //系统当前时间距纪元时间(秒)
  42. std::cout << "today to epoch: " << system_time << "seconds" << std::endl;
  43. return 0;
  44. }

运行结果:
在这里插入图片描述

以上。

发表评论

表情:
评论列表 (有 0 条评论,266人围观)

还没有评论,来说两句吧...

相关阅读

    相关 日期差值问题

    题目 有两个日期,求两个日期之间的天数,如果两个日期是连续的我们规定他们 之间的天数为两天 输入 有多组数据,每组数据有两行,分别表示两个日

    相关 日期差值

    问题 : 日期差值 题目描述 有两个日期,求两个日期之间的天数,如果两个日期是连续的我们规定他们之间的天数为两天。  输入 有多组数据,每组数据有