周数到月份

时间:2011-08-09 11:19:47

标签: objective-c date

鉴于我有特定年份的周数,我如何获得本周开始的月份名称? (使用Obj-c)

e.g。 2009年第2周应转换为2009年1月 2004年第51周应转为2004年12月

2 个答案:

答案 0 :(得分:1)

您可以使用日期库来执行此操作,但如果想要计算它,这里是一个解释的解决方案

你需要知道它是否是闰年。根据月份的不同,每个月有4周加上几天。

例如:

1月是4周加3天 ... 四月是4周加2天

存储每个月的额外天数(唯一可能变化的是2月,可能有28天或29天,具体取决于它是否是闰年)

$extra_days = (january => 3, march => 3, april => 2, december => 3);

计算2月额外天数(0或1),你必须计算它是否是闰年...你可以使用诸如 - >之类的操作来做到这一点。

$your_year mod 4

类似的东西:

if (($your_year - REFERENCE_LEAP_YEAR) mod 4 == 0) then "it's a leap year"

现在你可以计算每个月的额外天数。每个月有4个星期但你需要一个计数器来知道额外的日子是否满足一周。例如:

january = 3 extra days
-> weeks = 4 - extra_days = 3 febraury = 1 extra day
-> weeks = 8 - extra_days = 4 march = 3 extra days
-> weeks 12 - extra_days = 7
***now you have an extra week so..
-> weeks 13 - extra_days

...

答案 1 :(得分:0)

在问题中找到答案:get first day of given week

//convert week to month
    int weekNum = sdi.mWeek;
    const char *months[13]={"January","February","March","April","May","June","July","August","September","October","November","December","January"};
    struct tm curYear={0,0,0,1,0,sdi.mYear,0,0,0}; 
    time_t secsSinceEpoch=mktime(&curYear)+weekNum*86400*7;
    struct tm *candidateDate=gmtime(&secsSinceEpoch);    
    if (candidateDate->tm_wday!=1)
    {
        secsSinceEpoch+=(86400*(candidateDate->tm_wday-1)); 
        candidateDate=gmtime(&secsSinceEpoch);
    }    
    // [months[candidateDate->tm_mon]] returns month