时间格式化(把1535098068转成2018-08-24 16:07:48)

问题:

时间格式化(例如: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;
}

结果截图:

有什么问题欢迎留言交流。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

cai_niaocainiao

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值