如何根据日期计算周数?

36
如果我有一个日期,如何计算该年份对应的这个日期是第几周?
例如,在2008年,1月1日至1月6日在第1周,1月7日至13日在第2周,因此如果我的日期是2008年1月10日,我的周数将是2。
可以使用算法来开始编写代码,同时提供示例代码 - 我正在Windows上使用C++开发。

相关内容:

如何从MS SQL Server 2005中获取日期的周数?


现代C++11/14库可以轻松高效地完成这项任务:http://howardhinnant.github.io/iso_week.html - Howard Hinnant
15个回答

1
这是我的解决方案,但它不是用C++编写的。
NoOfDays = (CurrentDate - YearStartDate)+1
IF NoOfDays MOD 7 = 0 Then
    WeekNo = INT(NoOfDays/7)
ELSE
    WeekNo = INT(NoOfDays/7)+1
END 

0

0

我的假设是一年中的第一周可能包含最多7天,就像Olie的回答所示。 该代码无法处理周起始日不是星期日的文化,而这占据了世界上很大一部分。

tm t = ... //the date on which to find week of year

int wy = -1;

struct tm t1;
t1.tm_year = t.tm_year;
t1.tm_mday = t1.tm_mon = 1; //set to 1st of January
time_t tt = mktime(&t1); //compute tm

//remove days for 1st week
int yd = t.tm_yday - (7 - t1.tm_wday);
if(yd <= 0 ) //first week is now negative
  wy = 0;
else
  wy = (int)std::ceil( (double) ( yd/7) ); //second week will be 1 

0
time_t t = time(NULL);
tm* timePtr = localtime(&t);
double day_of_year=timePtr->tm_yday +1 ; // 1-365
int week_of_year =(int) ceill(day_of_year/7.0);

-1
/**
 * @brief WeekNo
 * @param yr
 * @param mon
 * @param day
 * @param iso
 * @return
 *
 *  Given a date, return the week number
 *  Note. The first week of the year begins on the Monday
 *  following the previous Thursday
 *  Follows ISO 8601
 *
 *  Mutually equivalent definitions for week 01 are:
 *
 *  the week with the year's first Thursday in it (the ISO 8601 definition)
 *  the week with the Thursday in the period 1 – 7 January
 *  the week starting with the Monday in the period 29 December – 4 January
 *  the week starting with the Monday which is nearest in time to 1 January
 *  the week ending with the Sunday in the period 4 – 10 January
 *  the week with 4 January in it
 *  the first week with the majority (four or more) of its days in the starting year
 *    If 1 January is on a Monday, Tuesday, Wednesday or Thursday, it is in week 01.
 *    If 1 January is on a Friday, Saturday or Sunday, it is part of week 52 or 53 of the previous year.
 *    the week with the year's first working day in it (if Saturdays, Sundays, and 1 January are not working days).
 ***    strftime has a conversion of struct tm to weeknumber.  strptime fills in tm struct**
 *   Code uses strptime, strftime functions.
 */

int WeekNo( int yr,int mon, int day, int iso)
{
    struct tm tm;
    char format[32];
    //memset(tm,0,sizeof(tm));
    sprintf(format,"%d-%02d-%02d",yr,mon,day);
    strptime(format, "%Y-%m-%d", &tm);
    // structure tm is now filled in for strftime

   strftime(format, sizeof(format), iso? "%V":"%U", &tm);

    //puts(format);
    return atoi(format);
}

调用 Weekno(2015,12,23,1); //获取 ISO 周数。 Weekno(2015,12,23,0) //获取非 ISO 周数


这种方法虽然优雅,但执行起来比直接执行代码要昂贵。然而,它与 C 语言函数 strptime 和 strftime 一样准确。 - Leslie Satenstein
对我没用 - 对所有日期都返回52。 - Aidan

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接