描述
相信大家在开发过程中经常需要获取当前的时间的问题, 下面总结了一些相关函,方便遇到的时候使用
- 计算两个时间相差多少分钟
//获取当前时间,格式为time_t
time_t current_time;
time(¤t_time);
//获取两个时间相隔多少分钟
long remainSec = difftime(time_t _Time1, time_t _Time2)
long minute = remainSec / 60;
- 不同格式的时间函数
//获取今日日期
inline std::string GetTodayDate()
{
time_t timep;
time(&timep);
char tmp[64];
strftime(tmp, sizeof(tmp), "%Y-%m-%d", localtime(&timep));
return tmp;
}
//获取今日时间
inline std::string GetCurrentDateTime()
{
time_t timep;
time(&timep);
char tmp[64];
strftime(tmp, sizeof(tmp), "%Y-%m-%d %H:%M:%S", localtime(&timep));
return tmp;
}
std::string get_local_time()
{
struct tm *t;
time_t tt;
time(&tt);
t = localtime(&tt);
char time[256];
sprintf_s(time,sizeof(time), "%4d/%02d/%02d %02d:%02d:%02d", t->tm_year + 1900, t->tm_mon + 1, t->tm_mday, t->tm_hour, t->tm_min, t->tm_sec);
return time;
}
//获取今日时间
inline std::string GetDateTime()
{
time_t timep;
time(&timep);
char tmp[64];
strftime(tmp, sizeof(tmp), "%Y-%m-%d %H%M%S", localtime(&timep));
return tmp;
}
//比较时间
inline bool CompareTime(const char* time1, const char* time2)
{
int year1, month1, day1, hour1, min1, sec1;
int year2, month2, day2, hour2, min2, sec2;
sscanf(time1, "%d-%d-%d %d:%d:%d", &year1, &month1, &day1, &hour1, &min1, &sec1);
sscanf(time2, "%d-%d-%d %d:%d:%d", &year2, &month2, &day2, &hour2, &min2, &sec2);
int tm1 = year1 * 10000 + month1 * 100 + day1;
int tm2 = year2 * 10000 + month2 * 100 + day2;
if (tm1 != tm2){
return false;
}
else{
//比较到分钟
tm1 = hour1 * 3600 + min1 * 60 ;
tm2 = hour2 * 3600 + min2 * 60 ;//将时分秒转换为秒数
if (tm1 == tm2){
return true;
}
else{
return false;
}
}
}