簡體   English   中英

奇怪的NSDate和NSDateFormatter行為

[英]Strange NSDate and NSDateFormatter behaviour

我想知道今年的一周。 這是我的代碼,也是正在計算的運行時值:

在此輸入圖像描述

為什么年份不正確? 嘗試過其他格式,比如yw,所有這些都給了我相同的結果。 如果我使用YYYY-W但這個問題確實自行解決了,那么我錯誤的月份/日期因為年份的計算方式不同。 只是為了獲取信息,這就是我用YYYY得到的:

在此輸入圖像描述

現在,在“yyyy”的情況下,第18周的日期是第29周的正確日期(見這里: http//www.epochconverter.com/date-and-time/weeknumbers-by-year.php )但是年份是僅在使用“YYYY”時更正(日期錯誤)。

那么最近怎么樣?

--------更新1 ---------

添加解決方案之后,在其中一個答案中提供:

在此輸入圖像描述

--------更新2 ----------

所以我的日期2000與“沒有定義年份”(之前是1970年)的價值相同。 見這里: http//openradar.appspot.com/12358210

--------更新3 ----------

系統信息(對於那些將嘗試復制此信息的人)。

XCode:版本4.6.2(4H1003)iOS:6.1 OSX:10.8.3

--------更新4 ----------

iOS 5.1在使用時提供了不同的結果:

在此輸入圖像描述

好像iOS 5.1在NSDateFormatter中不支持“w”。

編輯1 :這個答案沒有解釋OP看到的結果。 有關詳細信息,請參閱評論討論

編輯2 :我的機器上有非常特殊的結果。 在iOS 6上,本周根本不考慮System Preferences設置中的first day of week設置:

iOS 6總是返回:

2000-1 - > 2000年1月1日(星期六)

2001-1 - > 2001年1月6日(星期六)

即使我做[calendar setFirstWeekday: 3][dateFormatter setCalendar: calendar] ,也不會影響結果(不像iOS 5)! 這肯定是iOS 6 NSCalendar API中的一個錯誤。 我建議使用NSDateComponents或自己計算日期。 根據這個答案中的信息應該很容易 - 你可以假設ISO-8601(第一周最少4天,星期一開始),除非當然,你可以詢問用戶他們的偏好。


原始答案


這是發生了什么:

在您的語言環境中,一周中的最小天數為5 ,星期六的星期開始。

假設這是真的,第一周你將是5th Jan (周六) - 11th Jan 201311th Jan 2013 然后是第18周,你猜對了: 4th May 2013

為什么? 因為Apple遵循Unicode技術標准#35版本tr35-25 (在iOS 6+上)。

F.4 Week of Year

Values calculated for the Week of Year field range from 1 to 53 for the Gregorian calendar   
(they may have different ranges for other calendars). Week 1 for a year is the first week 
that contains at least the specified minimum number of days from that year. Weeks between 
week 1 of one year and week 1 of the following year are numbered sequentially from 2 to 52 
or 53 (if needed). For example, January 1, 1998 was a Thursday. If the first day of the 
week is MONDAY and the minimum days in a week is 4 (these are the values reflecting ISO 
8601 and many national standards), then week 1 of 1998 starts on December 29, 1997, and 
ends on January 4, 1998. However, if the first day of the week is SUNDAY, then week 1 of 
1998 starts on January 4, 1998, and ends on January 10, 1998. The first three days of 1998 
are then part of week 53 of 1997.

此外, YYYY-w是正確的格式。


如果您使用的是NSCalender,那么您將獲得所有這樣的組件,

NSDate *date = [NSDate date];
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSInteger units = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSWeekdayCalendarUnit;
    NSDateComponents *components1 = [calendar components:units fromDate:date];
    NSInteger year = [components1 year];
    NSInteger week=[components1 weekOfYear];

你能嘗試一下嗎?

NSString *dateString = @"2013-18";

NSDateFormatter *dateFormatter = [NSDateFormatter new];
[dateFormatter setDateFormat:@"yyyy-ww"];

NSDate *date = [dateFormatter dateFromString:dateString];
NSLog(@"Date: %@",date);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM