C++ 至1970-1-1的秒数转日期

 1 bool IsLeap(int year) {
 2     if (year > 1970 && year < 9999) {
 3         if (year % 400 == 0 || year % 100 != 0 && year % 4 == 0)
 4             return true;
 5     }
 6     return false;
 7 }
 8 
 9 // 1970-1-1起始时间 格式:xxxx-xx-xx
10 std::string TimeToDate(int64_t time) {
11     const char m_all_d[12] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
12     int64_t total_day = time / (60 * 60 * 24);
13     int year = 1970, month = 1, day = 1;
14 
15     while (year < 9999)
16     {
17         const int y_all_d = IsLeap(year) ? 366 : 365;
18 
19         if (total_day < y_all_d) {
20 
21             for (month = 1; month <= 12 && total_day > m_all_d[month - 1]; month++) {
22 
23                 if (month == 2 && IsLeap(year))
24                     total_day -= 29;
25                 else
26                     total_day -= m_all_d[month - 1];
27 
28             }
29             day += total_day;
30             break;
31         }
32         else {
33             total_day -= y_all_d;
34             year++;
35         }
36 
37     }
38 
39     return std::to_string(year) + '-' + std::to_string(month) + '-' + std::to_string(day);
40 }

最大年数我这里限制在9999年,to_string是C++11标准,需大于11标准才能编译的过。

posted @ 2021-04-17 23:35  YDD的铁皮锅  阅读(660)  评论(0编辑  收藏  举报