NSDate
のような文字列から次の誕生日を計算 (および作成) する最も簡単な方法は何でしょう@"02/29/1980"
か? (日月年)
3 に答える
3
これが私がそれをする方法です。
この場合、選択した日付はうるう日であるため、結果にはうるう年ではない年の翌日が表示されることに注意してください。「通常」の日付は、新年の同じ日に表示されます。
NSString *birthdayString = @"02/29/1980";
// Convert the string to a NSDate
NSDateFormatter *formatter = [NSDateFormatter new];
formatter.timeZone = [NSTimeZone timeZoneWithName:@"UTC"];
formatter.dateFormat = @"MM/dd/yyyy";
NSDate *birthday = [formatter dateFromString:birthdayString];
// Break the date apart into its components and change the year to the current year
NSCalendar *cal = [NSCalendar currentCalendar];
cal.timeZone = [NSTimeZone timeZoneWithName:@"UTC"];
NSDate *now = [NSDate date];
NSDateComponents *currentComps = [cal components:NSYearCalendarUnit fromDate:now];
NSDateComponents *birthdayComps = [cal components:NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit
fromDate:birthday];
birthdayComps.year = currentComps.year;
// Create the date from the modified components
NSDate *birthdayDate = [cal dateFromComponents:birthdayComps];
// Check to see if the birthday has passed yet this year, and if not add one year
if ([now compare:birthdayDate] == NSOrderedDescending)
{
NSDateComponents *oneYear = [NSDateComponents new];
oneYear.year = 1;
birthdayDate = [cal dateByAddingComponents:oneYear toDate:birthdayDate options:0];
}
NSLog(@"Next Birthday: %@", birthdayDate);
// Results: Next Birthday: 2013-03-01
于 2013-01-01T02:42:28.150 に答える
1
NSDateFormatterを使用して文字列を日付に変換します。次に、年を追加して、それに年を追加します。ボブはあなたのおじです。
于 2013-01-01T02:24:22.910 に答える