注意:未经测试,但考虑到当前年份,这应该可以做到:
const char *months[12]={"Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep",
"Oct","Nov","dec","Jan"};
/* Start with January 1st of the current year */
struct tm curYear={
0, // secs
0, // mins
0, // hours
1, // Day of month
0, // Month (Jan)
year,
0, // wday
0, // yday
0}; // isdst
/* Offset the number of weeks specified */
time_t secsSinceEpoch=mktime(&curYear)+
weekNum*86400*7; /* Shift by number of weeks */
struct tm *candidateDate=gmtime(&secsSinceEpoch);
/* If the candidate date is not a Monday, shift it so that it is */
if (candidateDate->tm_wday!=1)
{
secsSinceEpoch+=(86400*(candidateDate->tm_wday-1));
candidateDate=gmtime(&secsSinceEpoch);
}
printf("Mon %s %d",months[candidateDate->tm_mon],candidateDate->tm_mday\n");
例如,您可能需要根据给定年份的第 43 周的确切含义或符合 ISO-8601 来调整此代码中的公式。但是,这应该为您提供良好的样板代码以供您入门。您可能还想参数化星期几,以便它不被硬编码。
另外,如果需要,您可以通过截断结果来避免使用月份数组并格式化时间ctime
函数,它恰好显示的内容超出了您的要求。您将向其传递一个指向secsSinceEpoch
值并截断其输出以仅显示星期几、月份中的某一天和月份名称的缩写。