【C++】 时间戳转换,获取当前时间与自定义时间进行判断
输入时间的格式与ubuntu下获取的时间格式一致。
(图片来源网络,侵删)
例如:2024-06-26 12:00:00。
为了方便进行时间之间的比较,将时间转换成时间戳再进行判断。
代码
#include 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 cout
文章版权声明:除非注明,否则均为主机测评原创文章,转载或复制请以超链接形式并注明出处。