最近需要实现一个判断当前是否是上班时间段内,但是需要从文件中读取特定的格式时间时间段
格式: 00:00-12:34|13:56-15:00(不确定几个时间段,每个时间段以|分隔)
读取特定格式时间并转化不难但是挺麻烦的
cpp
//获得当前中国时区时间
void getNowTime(char* bufTime,int bufTimeLength)
{
//setTimeZone("Asia/ShangHai");
time_t now;
struct tm *info;
time(&now);
info = localtime(&now);
info->tm_hour=(info->tm_hour)+8;
strftime(bufTime,bufTimeLength,"%Y-%m-%d %H:%M:%S",info);
return ;
}
//解析时间段 时间段格式 00:00-12:34
void parseTime(const char* timeStr,int* hour,int* minute)
{
sscanf(timeStr,"%d:%d",hour,minute);
}
void parseTimePar(const char* timeParStr,int* startHour,int* startMinute,int* endHour,int* endMinute)
{
char startTime[6],endTime[6];
sscanf(timeParStr,"%5[^-]-%5s",startTime,endTime);
parseTime(startTime,startHour,startMinute);
parseTime(endTime,endHour,endMinute);
}
//判断当前时间是否在上班时间
int inWork(int nowHour,int nowMinute,int startHour,int startMinute,int endHour,int endMinute)
{
int now = nowHour*60+nowMinute;
int start = startHour*60+startMinute;
int end = endHour*60+endMinute;
//printf("now:%d:%d\nstart:%d:%d\nend:%d:%d\n",nowHour,nowMinute,startHour,startMinute,endHour,endMinute);
if(start>end)
{
printf("startTime>endTime====>now is all day\n");
return 1;
}
if(now>=start&&now<=end)
{
return 1;
}
return 0;
}
//从文件中读取时间字符串
//格式:00:00-12:34|12:35-12:36|14:33-14:34|...(不确定的多个时间段,每个时间段以|分隔)
int workOrRest()
{
time_t t1,tim;
struct tm *p;
time(&t1);
p = localtime(&t1);
int nowHour = (p->tm_hour)+8;
int nowMinute = p->tm_min;
int workFlag=0;
FILE *fp;
char loadFile[256];
char line[256];
strcpy(loadFile,"/home/projects/timeSet.txt");
fp = fopen(loadFile,"r");
if(fp==NULL)
{
printf("can not load file! function in workOrRest\n");
return -1;
}
if(!fgets(line,sizeof(line),fp))
{
printf("file error!\n");
return -1;
}
//char* first = strtok(line,"|");
//if(first)
//{
// printf("%s\n",first);
//}
//char* second = NULL;
char *timeParStr;
char *ptr = line;
while((timeParStr = strtok_r(ptr,"|",&ptr)))
{
int startHour,startMinute,endHour,endMinute;
parseTimePar(timeParStr,&startHour,&startMinute,&endHour,&endMinute);
if(inWork(nowHour,nowMinute,startHour,startMinute,endHour,endMinute))
{
workFlag=1;
break;
}
//printf("workFlag:%d\n",workFlag);
}
return workFlag;
}
//调用示例
int main()
{
if(workOrRest())
printf("上班时间段\n");
else
printf("休息时间\n");
}