【C++】 时间戳转换,获取当前时间与自定义时间进行判断

输入时间的格式与ubuntu下获取的时间格式一致。
例如:2024-06-26 12:00:00。
为了方便进行时间之间的比较,将时间转换成时间戳再进行判断。

代码

#include <iostream>
using namespace std;

time_t transferToTimeStamp(string str)
{
	// the format of time need to be as the same as the time in shell.
	// for example: "2024-06-26 12:00:00".
	tm tempTm;                                 // use tm structure.
	int year, month, day, hour, minute, second;// catch every time parameter.
	year   = atoi((str.substr(0, 4)).c_str());
	month  = atoi((str.substr(5, 2)).c_str());
	day    = atoi((str.substr(8, 2)).c_str());
	hour   = atoi((str.substr(11, 2)).c_str());
	minute = atoi((str.substr(14, 2)).c_str());
	second = atoi((str.substr(17, 2)).c_str());

	tempTm.tm_year  = year - 1900;              // the range of year in tm start from 1990, so need to reduce 1990.      
	tempTm.tm_mon   = month - 1;                 // the range of month in tm from 0 to 11, so need to reduce 1.
	tempTm.tm_mday  = day;                         
	tempTm.tm_hour  = hour;                        
	tempTm.tm_min   = minute;                       
	tempTm.tm_sec   = second;                       
	tempTm.tm_isdst = 0;                       // not daylight time.

	time_t timeStamp = mktime(&tempTm);        // transfer tm to time_t.
	return timeStamp;                                 
}

int main(void)
{
	// 1. get current timestamp.
	time_t now;                                                                                                                      
	int unixTime = (int)time(&now);

	// 2. set up your detect time and get timeStamp
	string detectTime = "2024-06-26 12:00:00";
	time_t t_strnowdate_time = transferToTimeStamp(detectTime);
	
	// 3. judge time
	if((int)t_strnowdate_time > (int)unixTime)
	{
		cout << "greater than current time." << endl;
	}
	else
	{
		cout << "smaller than current time." << endl;
	}

	// 4. display in terminal through format:"%Y-%m-%d %H:%M:%S"
	time_t tick = (time_t)unixTime;  
	struct tm tm;
	char s[100];
	tm = *localtime(&tick);
	strftime(s, sizeof(s), "%Y-%m-%d %H:%M:%S", &tm);  

	printf("current time: %d: %s\n", (int)unixTime, s);
	printf("detect  time: %d: ", (int)t_strnowdate_time);
	cout << detectTime <<endl;

	return 0;
}

CmakeList

# cmakelists: demo
cmake_minimum_required (VERSION 3.8)
project (time VERSION 1.0.0)

add_executable (time main.cpp)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值