也许你应该看看boost::date_time::gregorian。使用它,您可以编写这样的函数:
#include <boost/date_time/gregorian/gregorian.hpp>
// Get the date for a given year, week and weekday(0-6)
time_t *GetDateFromWeekNumber(int year, int week, int dayOfWeek)
{
using namespace boost::gregorian;
date d(year, Jan, 1);
int curWeekDay = d.day_of_week();
d += date_duration((week - 1) * 7) + date_duration(dayOfWeek - curWeekDay);
tm tmp = to_tm(d);
time_t * ret = new time_t(mktime(&tmp));
return ret;
}
不幸的是,他们的日期格式与您的不同 - 他们从星期日开始计算星期几,即Sunday = 0, Monday = 1, ..., Saturday = 6
. 如果它不能满足您的需求,您可以使用这个稍作改动的函数:
#include <boost/date_time/gregorian/gregorian.hpp>
// Get the date for a given year, week and weekday(1-7)
time_t *GetDateFromWeekNumber(int year, int week, int dayOfWeek)
{
using namespace boost::gregorian;
date d(year, Jan, 1);
if(dayOfWeek == 7) {
dayOfWeek = 0;
week++;
}
int curWeekDay = d.day_of_week();
d += date_duration((week - 1) * 7) + date_duration(dayOfWeek - curWeekDay);
tm tmp = to_tm(d);
time_t * ret = new time_t(mktime(&tmp));
return ret;
}
编辑:
经过一番思考,我找到了一种无需使用 boost 即可实现相同功能的方法。这是代码:
警告:以下代码已损坏,请勿使用!
// Get the date for a given year, week and weekday(1-7)
time_t *GetDateFromWeekNumber(int year, int week, int dayOfWeek)
{
const time_t SEC_PER_DAY = 60*60*24;
if(week_day == 7) {
week_day = 0;
week++;
}
struct tm timeinfo;
memset(&timeinfo, 0, sizeof(tm));
timeinfo.tm_year = year - 1900;
timeinfo.tm_mon = 0;
timeinfo.tm_mday = 1;
time_t * ret = new time_t(mktime(&timeinfo)); // set all the other fields
int cur_week_day = timeinfo.tm_wday;
*ret += sec_per_day * ((week_day - cur_week_day) + (week - 1) * 7);
return ret;
}
编辑2:
是的, EDIT中的代码完全被破坏了,因为我没有花足够的时间来理解如何分配周数。