2011-08-09 71 views
2

鑑於我有一個特定年份的星期編號,我如何得到該周開始的月份名稱? (使用Obj-c)週數到月份

例如2009年的2周應轉換爲2009年1月 和51周2004年的應轉換爲2004年12月

回答

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 
1

您可以使用最新的圖書館這樣做,但如果想計算的話,這裏是一個解釋的解決方案

你需要知道這是不是一個閏年。每個月有4周加上幾個月的時間取決於月份。

例如:

一月爲4周加3天 ... 四月爲4周加2天

商店天額外每個月(可以變化的只有一個是二月可能有28或29天,這取決於它是否是一個閏年)

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

計算二月額外的天數(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 

...