您可以使用NSCalendar
獲取日期的月份,日期和年份組件,操作它們並重新組合它們。這是一些示例代碼。
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *dateComponents = [calendar components:(NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit) fromDate:date];
[otherDateComponents setYear:[dateComponents year]];
[otherDateComponents setMonth:[dateComponents month]];
[otherDateComponents setDay:[dateComponents day]];
NSDate *newDate = [calendar dateFromComponents:otherDateComponents];
注意的是,由於當前日曆是特定於語言環境,你回來的值不會在所有設備上的相同。你可能希望爲你的目的指定一個特定的日曆。 NSGregorianCalendar
是西方最常用的一種。
'NSDateFormatterMediumStyle'是區域特異性的。雖然不太可能,但它可能不會返回你想要的字段。只要您可以承擔公曆,您就可以使用明確的方法(如接受的解決方案或自定義格式字符串)更安全。 – warrenm 2010-06-01 17:32:06