【C++】写一个函数实现系统时间与输入时间进行比较

目录

1 代码

2 运行结果

 

时间比较函数:

输入为字符串2023-7-28,将字符串分解为年、月、日信息。

获取系统时间2023-7-24,然后将输入时间和系统时间进行比较,输出比较结果。

1 代码

#include <ctime>
#include<iostream>
#include<vector>
using namespace std;
void StrSplit(string str_in, const char split_c, vector<string>& str_results)
{
    if (str_in == ""){
        std::cout << "error : str is null" << std::endl;
        return;
    }
    size_t pos = str_in.find(split_c);
    while (pos != str_in.npos)
    {
        string temp = str_in.substr(0, pos);
        str_results.push_back(temp);
        str_in = str_in.substr(pos + 1, str_in.size());
        pos = str_in.find(split_c);
    }
}
string TimeCompare(string databaseTime){
    vector<string> tmp_str;
    StrSplit(databaseTime + "-", '-', tmp_str);
    unsigned int dayin, daysys, year=0,mon=0,day=0;
    if(tmp_str.size() == 3){
        year = stoi(tmp_str[0]);
        mon = stoi(tmp_str[1]);
        day = stoi(tmp_str[2]);
    }else{
        std::cout<< "Time format error !!!"<<std::endl;
        return "error";
    }
    dayin = year*10000+mon*100+day;
    time_t now = time(NULL);
    tm *tm_t = localtime(&now);
    daysys =(tm_t->tm_year + 1900)*10000 + (tm_t->tm_mon+1)*100 + tm_t->tm_mday;
    cout<<"SystemTime: "<<tm_t->tm_year + 1900<<"-"<<tm_t->tm_mon+1<<"-"<<tm_t->tm_mday<<endl;
    if(dayin > daysys) {
        return "big";
    }else if(dayin < daysys) {
        return "small";
    }else{
        return "equal";
    }
}
int main()
{
    cout<<"Input1: "<<"2023-7-28"<<endl;
    cout<<TimeCompare("2023-7-28")<<endl;
    cout<<"Input2: "<<"2022-6-3"<<endl;
    cout<<TimeCompare("2022-6-3")<<endl;
}

2 运行结果

猜你喜欢

转载自blog.csdn.net/wss794/article/details/131951867