C++如何将日期运算之后格式化为日期字符串
如题,比如给一个时间增加多少秒后转化为 日期-时间 的格式标准库里有嘛?
还是得自己写?
#include <iostream> #include <chrono> using namespace std; using namespace std::chrono; //using namespace std::chrono_literals; int main( void ) { year_month_day a { year(2022), month(11), day(27) }; cout << a << endl; auto b = local_days(a) + hours(25) + minutes(12) + seconds(31); cout << b << endl; }
#include <time.h> #include <stdio.h> time_t TimeFromLocal( int year, int mon, int day, int hour, int min, int sec ) { struct tm t; t.tm_year = year-1900; t.tm_mon = mon-1; t.tm_mday = day; t.tm_hour = hour; t.tm_min = min; t.tm_sec = sec; return mktime(&t); } void PrintTm( const struct tm* ptm ) { printf( "%04d年%02d月%02d日 %02d时%02d分%02d秒 " , ptm->tm_year+1900, ptm->tm_mon+1, ptm->tm_mday , ptm->tm_hour, ptm->tm_min, ptm->tm_sec ); printf( "(本年第%d天,星期%d)\n" , ptm->tm_yday+1, ptm->tm_wday ); } int main( void ) { time_t t = TimeFromLocal( 2000, 2, 3, 4, 5, 6 ); PrintTm( localtime(&t) ); t += 100000; // 增加 100000秒 即 1天3小时46分钟40秒 PrintTm( localtime(&t) ); return 0; }