Table of contents
Time comparison function:
The input is the string 2023-7-28, and the string is decomposed into year, month, and day information.
Get the system time 2023-7-24, then compare the input time with the system time, and output the comparison result.
1 code
#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 Running results