使用time函数和localtime函数实现获取当前时间,以及解决visual studio 报错localtime不安全的问题

1、time函数返回的是距离1970-1-1,00:00:00所经过的秒数
成功:返回秒数
失败:返回-1
头文件是

#include<ctime>
(或者c版本)#include<time.h>

一般用法

#include<iostream>
#include<ctime>
using namespace std;
int main()
{
	const time_t t=time(NULL);
    cout<<"t="<<t<<endl; 
}

输出结果为
在这里插入图片描述

2、如果想具体输出年月日时分秒的话,配合localtime就可以了

成功:返回struct tm*结构体
失败:NULL

#include<iostream>
#include<ctime>
using namespace std;
int main()
{
    const time_t t=time(NULL);
    cout<<"t="<<t<<endl; 
    struct tm* systemtime=localtime(&t);
    cout<<"year="<<1900+systemtime->tm_year<<endl;
    cout<<"month="<<1+systemtime->tm_mon<<endl;
    cout<<"day="<<systemtime->tm_mday<<endl;
    cout<<"hour="<<systemtime->tm_hour<<endl;
    cout<<"minute="<<systemtime->tm_min<<endl;
    cout<<"second="<<systemtime->tm_sec<<endl;
}

运行结果是
在这里插入图片描述

3、解决visual studio 报错localtime不安全的问题

把localtime 换成localtime_s,其中的参数还需要进行变换,第一个参数是结构体的参数,第二个是ttime_t的名字

具体代码如下

#include<iostream>
#include<ctime>
#include<sstream>
using namespace std;
int main()
{
	//订单编号:年月日+时分秒
	ostringstream number;
	cout << "订单编号为: ";
	const time_t t = time(NULL);
	struct tm systemtime;
	localtime_s(&systemtime, &t);
	//年
	number << 1900 + systemtime.tm_year;


	//月
	if (systemtime.tm_mon < 10)
	{
		number << 0;
	}
	number << systemtime.tm_mon + 1;
	//日
	if (systemtime.tm_mday < 10)
	{
		number << 0;
	}
	number << systemtime.tm_mday;
	//时
	if (systemtime.tm_hour < 10)
	{
		number << 0;
	}
	number << systemtime.tm_hour;
	//分
	if (systemtime.tm_min < 10)
	{
		number << 0;
	}
	number << systemtime.tm_min;
	//秒
	if (systemtime.tm_sec < 10)
	{
		number << 0;
	}
	number << systemtime.tm_sec;
	cout << number.str() << endl;

}



运行结果是,年月日时分秒
在这里插入图片描述
我这个代码使用vs2019写的,devc++报错
在这里插入图片描述

上面的localtime的代码我是用devc++写的,不报错,但是vs2019报错,看你用什么编译器吧

猜你喜欢

转载自blog.csdn.net/qq_45721778/article/details/106178468