Parse time periods
I have time format, that looks like this:
10:30开发者_运维技巧-12:30,18:00-00:30 Mo-We,Th,Sa
and
Mo-Fr 08:00-13:30; Sa 08:00-12:30
Is there any easy and fast way to parse this? I need a function to compare current time to date in this formats.
Is this standart format ?
No, it's not a standard format. I'll try to split your problem in a few key parts:
1) Data storage:
Since the problem is limited to the days of the week, you could create an array of pairs of tm structs for each day of the week:
#include <time.h>
typedef tm interval[2];
typedef interval* daysofweek[7];
void main(void)
{
int number_of_intervals = 2; //this must be calculated for each day but to exemplify how you could store your data I initialised it to 2
interval *intervals;
intervals = (interval*)malloc(number_of_intervals);
daysofweek d;
d[0] = intervals; //you must set the intervals for each day
}
2) Parsing
You should define a set of rules based on the sintax of the strings. From the two strings you exemplified I would define the following rules:
- split and treat separately all strings based on the
;
character - split the resulted strings into a part with numerals (plus
-
,:
and,
) respectively a part with characters - parse the part with numerals and create the time intervals
- parse the part with characters and populate the array for each day, keep track of all the days so that you can initialize the remaining days with 0 second intervals
3) Comparison
After you populated your data structure, you can parse it and deduce if you are in an interval or not by using the comparison functions found in ctime.
HTH, JP.
P.S. if you would use C++ and STL instead of plain C, the task would be a bit easier.
精彩评论