时间戳转特定的时间格式
在<time.h>库函数中,定义了时间相关数据结构,一般使用time_t来表示时间戳,可以用int,long来表示,tm表示时间相关数据结构
#include<iostream>
#include<time.h>
int main() {
time_t timeStamp1 = (time_t)0;
time_t timeStamp2 = (time_t)3600;
struct tm time1;
struct tm time2;
localtime_s(&time1, &timeStamp1);
localtime_s(&time2, &timeStamp2);
printf("%d-%d-%d %d:%d:%d\n", time1.tm_year + 1900, time1.tm_mon + 1,time1.tm_mday, time1.tm_hour, time1.tm_min, time1.tm_sec);
printf("%d-%d-%d %d:%d:%d\n", time2.tm_year + 1900, time2.tm_mon + 1,time2.tm_mday, time2.tm_hour, time2.tm_min, time2.tm_sec);
return 0;
}
1970-1-1 8:0:0
1970-1-1 9:0:0
之前很多博文转换应该使用localtime()方法,但是新版的VS并不能使用
1>C:\Users\Administrator.DESKTOP-2EJND90\Desktop\temp\test\test.cpp(68): error C4996: ‘localtime’: This function or variable may be unsafe. Consider using localtime_s instead. To disable deprecation, use _CRT_SECURE_NO_WARNINGS. See online help for details.
查阅发现,localtime并不是线程安全的,观察localtime和localtime_s的调用发现,localtime在使用时,我们只需定义一个时间戳指针,并不需要为时间相关的那个数据结构指针申请空间,而指针必须要指向内存空间才可以使用,其实申请空间的动作由函数自己完成,这样在多线程的情况下,如果有另一个线程调用了这个函数,那么指针指向的struct tm结构体的数据就会改变。在localtime_s与localtime_r调用时,定义的是struct tm的结构体,获取到的时间已经保存在struct tm中,并不会受其他线程的影响。
自定义时间格式字符串转成时间戳
一开始设定好传入字符串格式,截取不同地方的字符串,赋值给时间戳数据结构struct tm,我这里用正则截取了需要的时间信息
#include <iostream>
#include <time.h>
#include<regex>
using namespace std;
int standard_to_stamp(std::string str_time){
struct tm stm;
int iY, iM, iD, iH, iMin, iS;
memset(&stm, 0, sizeof(stm));
//正则提取日期信息
std::regex re("(\\d+)/(\\d+)/(\\d+)(\\s)(\\d+):(\\d+):(\\d+)");
std::smatch sm;
std::regex_search(str_time, sm, re);
std::string yearString = sm[1];
std::string monthString = sm[2];
std::string dayString = sm[3];
std::string hourString = sm[5];
std::string minuteString = sm[6];
std::string secondString = sm[7];
//数据结构赋值
iY = atoi(yearString.c_str());
iM = atoi(monthString.c_str());
iD = atoi(dayString.c_str());
iH = atoi(hourString.c_str());
iMin = atoi(minuteString.c_str());
iS = atoi(secondString.c_str());
stm.tm_year = iY - 1900;
stm.tm_mon = iM - 1;
stm.tm_mday = iD;
stm.tm_hour = iH;
stm.tm_min = iMin;
stm.tm_sec = iS;
printf("%d-%0d-%0d %0d:%0d:%0d\n", iY, iM, iD, iH, iMin, iS);
return (int)mktime(&stm);
}
int main(){
int stampTime1 = standard_to_stamp("1970/1/1 10:00:00");
cout << stampTime1 << endl;
return 0;
}
1970-1-1 10:0:0
7200
快速获取当前时间的方法(CTime)以及坑
简单例子
#include <iostream>
#include "atltime.h"
using namespace std;
int main() {
CTime timeNow = CTime::GetCurrentTime();
int year = timeNow.GetYear();
std::cout << year;
return 0;
}
2019
存在问题
会和std::max,std::min两个方法不兼容
报一个非常奇怪的错误
解决方法是把(std::min)括号括起来就好
参考
localtime、localtime_s、localtime_r的使用
c,c++中时间戳与标准时间间的相互转换
std::min,std::max 与 MFC冲突的解决