自己常用时间处理函数记录
程序员文章站
2024-01-21 23:41:52
...
记录自己常用的时间处理函数,方便以后查阅。
#ifndef __SELFTIME__
#define __SELFTIME__
#include <stdio.h>
#include <time.h>
#include <string>
#define TIME_ZONE_OFFSET_SECONDS (8*3600) //东八区
const int one_hour_secs = 3600;
const int one_day_secs = 86400; //24 * 3600
class SelfTime
{
public:
SelfTime(){};
~SelfTime(){};
//获取当前系统时间
static int SelfTime::getCurrentTime(){
long ltime = time(nullptr);
return ltime;
}
//获取时间的具体描述
static struct tm SelfTime::getLocalTime(unsigned int goalTime/*if 0 get current time*/){
struct tm *now;
time_t tt;
if (goalTime != 0){
tt = goalTime;
}
else{
tt = SelfTime::getCurrentTime();
}
tt += TIME_ZONE_OFFSET_SECONDS;
now = gmtime(&tt);
return *now;
}
//判断当前时间和目标时间日期是否相同(目标时间需要不大于当前时间)
static bool isSameDate(unsigned int goalTime/*<= current time*/){
if (goalTime == 0){
return false;
}
long resetTime = SelfTime::getResetTime();
auto goalTm = SelfTime::getLocalTime(goalTime);
auto nowTm = SelfTime::getLocalTime(0);
int r_dis = goalTm.tm_hour * one_hour_secs + goalTm.tm_min * 60 + goalTm.tm_sec;
int dis = nowTm.tm_hour * one_hour_secs + nowTm.tm_min * 60 + nowTm.tm_sec;
if (goalTm.tm_year == nowTm.tm_year
&&goalTm.tm_mon == nowTm.tm_mon
&&goalTm.tm_mday == nowTm.tm_mday)
{
if ((r_dis <= resetTime&&dis <= resetTime)
|| (dis >= resetTime&&r_dis >= resetTime))
{
return true;
}
}
else{
if (SelfTime::getCurrentTime() - goalTime<one_day_secs
&&r_dis >= resetTime
&&dis <= resetTime)
{
return true;
}
}
return false;
}
//判断当前时间和目标时间是否同周
static bool isSameWeek(unsigned int goalTime)
{
int monday0 = SelfTime::getRelativeMonday0PassSecs();
auto now = SelfTime::getCurrentTime();
int disTime = now - goalTime;
return disTime <= monday0;
}
//获取相对当天0点过了多少秒
static int getRelativeDay0PassSecs()
{
auto now = SelfTime::getLocalTime(0);
long disTime = now.tm_hour * one_hour_secs + now.tm_min * 60 + now.tm_sec;
return disTime;
}
//获取相对本周周一0点过了多少秒
static int getRelativeMonday0PassSecs()
{
auto now = SelfTime::getLocalTime(0);
auto curWDay = now.tm_wday;
if (now.tm_wday == 0)
{
curWDay = 7;
}
auto disTime = ((curWDay - 1) * one_day_secs) + now.tm_hour * one_hour_secs + now.tm_min * 60 + now.tm_sec;
return disTime;
}
//获取每天的重置时间(即跨天的时间点)
static int getResetTime(){
return 0;
}
private:
};
#endif