2017-03-03 130 views
1

我有這樣一段代碼NSDateComponents返回意外的結果

NSDateComponents *comps = [[NSCalendar currentCalendar] components:(NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay) fromDate:sender.date]; 
[comps setTimeZone:[NSTimeZone timeZoneWithName:@"UTC"]]; 
NSDate *converted = [[NSCalendar currentCalendar] dateFromComponents:comps]; 

Sender.date可以輸出到控制檯像

1963年2月23日上午12:00:00 +0000

comps.day UTC會給我22.我預計從23在UTC的帽子發送者值明顯包含等於23的日分量。

這與12am有什麼關係嗎?我在這裏錯過了什麼?

謝謝!

+1

這是說'22',因爲它顯示在你自己的時區給你,而字符串是顯示在格林尼治標準時間/ UTC /祖魯日期。 – Rob

+0

考慮簡單地使用'NSDate *轉換= [[NSCalendar currentCalendar] startOfDayForDate:sender.date];' – vadian

+0

@Rob但我已經爲DateComponents對象設置了UTC。所以我希望它輸出的UTC值記錄下來。 –

回答

1

這取決於你的意圖。試想一下:

NSString *string = @"1963-02-23 12:00:00 am +0000"; 
NSDateFormatter *formatter = [[NSDateFormatter alloc] init]; 
formatter.dateFormat = @"yyyy-MM-dd hh:mm:ss a X"; 
NSDate *date = [formatter dateFromString:string]; 
NSCalendar *calendar = [NSCalendar currentCalendar]; 
calendar.timeZone = [NSTimeZone timeZoneForSecondsFromGMT:0]; 
NSDateComponents *comps = [calendar components:NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay fromDate:date]; 
NSLog(@"%@", comps); 

這將報告:

< NSDateComponents:0x610000140420 >
日曆年份:1963年
月:2
閏月:沒有
日:23

然後我就可以將其轉換成一個日期在我們當地時區有:

NSDate *converted = [[NSCalendar currentCalendar] dateFromComponents:comps]; 
NSLog(@"%@", converted); 

這將顯示,截至午夜在我的本地時區(GMT-8),這是上午8點在格林尼治標準時間:

1963年2月23日08:00:00 +0000

但是當我使用一個格式來顯示給用戶,但是,它表明,要在我的本地時區:

NSDateFormatter *outputFormatter = [[NSDateFormatter alloc] init]; 
outputFormatter.dateStyle = NSDateFormatterMediumStyle; 
outputFormatter.timeStyle = NSDateFormatterMediumStyle; 
NSLog(@"%@", [outputFormatter stringFromDate:converted]); 

,將顯示:

1963年2月23日,上午12:00:00

顯然,使用NSDateFormatterNoStyletimeStyle如果你不想來顯示時間,但我包括它只是爲了告訴你真正發生了什麼。

就我個人而言,我覺得上述所有都很複雜。我猜測原始字符串試圖反映與任何特定時間和/或時區無關的日期(例如生日,週年紀念等),那麼我認爲如果您省略時間和時區,一切都會容易得多來自原始字符串的信息,並以yyyy-MM-dd格式捕獲日期,並將其保留。然後,這簡化了大部分上述代碼。

我可能會建議澄清你的實際意圖,你爲什麼要做你正在做的事情,我們可能會提供更好的建議。

+0

你是英雄。非常感謝你。 –