有没有办法避免在以下代码中对gmtime()
进行如此多的调用:
unsigned int get_day(unsigned int timestamp)
{
time_t t = timestamp;
struct tm * timeval = gmtime(&t);
return timeval->tm_wday;//0 = sun
}
unsigned int get_start_of_day(unsigned int timestamp)
{
int day_of_w = get_day(timestamp);
while(get_day(timestamp-3600) == day_of_w) timestamp -= 3600;
while(get_day(timestamp-60) == day_of_w) timestamp -= 60;
while(get_day(timestamp-1) == day_of_w) timestamp--;
return timestamp;
}
答案 0 :(得分:0)
time_t get_start_of_day(time_t timestamp)
{
// convert timestamp to tm*
struct tm* my_tm = gmtime(×tamp);
// zero out fractions of a day.
// gmtime returns a pointer to mutable struct
my_tm->tm_sec = 0;
my_tm->tm_min = 0;
my_tm->tm_hour = 0;
// convert back to timestamp
timestamp = mktime(my_tm);
return timestamp;
}