输入时间的格式与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)