C++年月日时分秒与秒数互相转换

一.tm结构

struct tm
{
	int tm_sec; //秒,正常范围0-59, 但允许至61
	int tm_min; //分钟,0-59
	int tm_hour; //小时, 0-23
	int tm_mday; //日,即一个月中的第几天,1-31
	int tm_mon; //月, 从一月算起,0-11/ 1+p->tm_mon;
	int tm_year; //年, 从1900至今已经多少年/ 1900+ p->tm_year
	int tm_wday; //星期,一周中的第几天, 从星期日算起,0-6
	int tm_yday; //从今年1月1日到目前的天数,范围0-365
	int tm_isdst; //日光节约时间的旗标
};

二.年月日时分秒与秒数互相转换

#include "stdafx.h"
#include <time.h>
#include <iostream>
using namespace std;

int _tmain(int argc, _TCHAR* argv[])
{
	//已知当前时间2021-3-12 11:52:38
	//转换为秒
	struct tm time;
	time.tm_year = 2021 - 1900;//tm中的年份比实际年份小1900,需要减掉
	time.tm_mon = 3 - 1;//tm中的月份从0开始,需要减1
	time.tm_mday = 12;
	time.tm_hour = 11;
	time.tm_min = 52;
	time.tm_sec = 38;
	time_t ltime_new = mktime(&time);

	cout << "------------将2021-3-12 11:52:38转换为秒------------" << endl;
	cout << ltime_new << endl;
	cout << "------------将2021-3-12 11:52:38转换为秒------------" << endl;
	cout << "\r\n" << endl;

	//将秒数转换为年月日时分秒
	struct tm newTime;
	newTime = *localtime( &ltime_new );  /* Convert to local time. */
	
	cout << "------------------将秒数转换为时间------------------" << endl;
	//星期,一周中的第几天, 从星期日算起,0-6
	char week[10];
	switch(newTime.tm_wday)
	{
	case 0:
		sprintf_s(week, "%s", "星期日");
		break;
	case 1:
		sprintf_s(week, "%s", "星期一");
		break;
	case 2:
		sprintf_s(week, "%s", "星期二");
		break;
	case 3:
		sprintf_s(week, "%s", "星期三");
		break;
	case 4:
		sprintf_s(week, "%s", "星期四");
		break;
	case 5:
		sprintf_s(week, "%s", "星期五");
		break;
	case 6:
		sprintf_s(week, "%s", "星期六");
		break;
	default:
		sprintf_s(week, "%s", "有星期八吗?");
		break;
	}

	int nYDay = newTime.tm_yday + 1;//tm从今年1月1日到目前的天数,范围0-365,需加1
	int nYear = newTime.tm_year + 1900;//tm中的年份比实际年份小1900,需加1900
	int nMon = newTime.tm_mon + 1;//月, 从一月算起,范围0-11,需加1
	int nMDay = newTime.tm_mday;//日
	int nHour = newTime.tm_hour;//时
	int nMin = newTime.tm_min;//分
	int nSec = newTime.tm_sec;//秒
	
	cout << "当前时间为:一年中的第" << nYDay << "天" << " " << week << " "
		<< nYear << "-" << newTime.tm_mon+1 << "-" << newTime.tm_mday 
		<< " " << newTime.tm_hour << ":" << newTime.tm_min << ":" << newTime.tm_sec 
		<< endl;
	cout << "------------------将秒数转换为时间------------------" << endl;

	return 0;
}

三.运行结果

------------将2021-3-12 11:52:38转换为秒------------
1615521158
------------将2021-3-12 11:52:38转换为秒------------


------------------将秒数转换为时间------------------
当前时间为:一年中的第71天 星期五 2021-3-12 11:52:38
------------------将秒数转换为时间------------------
请按任意键继续. . .
  • 5
    点赞
  • 23
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

whxj12

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

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

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

打赏作者

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

抵扣说明:

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

余额充值