问题:
时间格式化(例如:1535098068转成2018-08-24 16:07:48)
时间从1970年开始计算,且时间校正为UTC+8
语言:C++
编译软件: vs2013
代码示例:(输入秒即会转化为对应时间格式)
#include <iostream>
#include <string>
#include <stdlib.h>
using namespace std;
struct _xtime{
int year;
int month;
int day;
int hour;
int minute;
int second;
};
void xSeconds2Data(unsigned long seconds, _xtime &time)
{
static unsigned int month[12] = { 31,
28, 31, 30, 31, 30,
31, 31, 30, 31, 30, 31 };
unsigned int days;
unsigned short leap_y_count;
time.second = seconds % 60;
seconds /= 60;
time.minute = seconds % 60;
seconds += 8 * 60; //时区矫正,转为UTC+8
seconds /= 60;
time.hour = seconds % 24;
days = seconds / 24;
leap_y_count = (days + 365) / 1461;//过去了多少个闰年(4年一闰)
if (((days + 366) % 1461) == 0)//闰年的最后一天
{
time.year = 1970 + (days / 366);
time.month = 12;
time.day = 31;
return;
}
days -= leap_y_count;
time.year = 1970 + (days / 365);
days %= 365;
days = 01 + days;
if ((time.year % 4) == 0)//闰年
{
if (days>60)
{
--days;
}
else{
if (days == 60){ //二月的最后一天
time.month = 2;
time.day = 29;
return;
}
}
}
for (time.month = 0; month[time.month]<days; time.month++)
{
days -= month[time.month];
}
++time.month;
time.day = days;
}
int main()
{
string strTime; //存时间格式化后的字符串
long lTime ;
cin >> lTime;
_xtime time;
xSeconds2Data(lTime, time);
char cArrTime[32] = "\0";
_snprintf_s(cArrTime, sizeof(cArrTime)-1, "%4d-%02d-%02d %02d:%02d:%02d", time.year, time.month, time.day, time.hour, time.minute, time.second);
strTime = string(cArrTime);
cout << strTime<<endl;
system("pause");
return 0;
}
结果截图:
有什么问题欢迎留言交流。