从获取当前date,但将时间设置为上午10:00

如何重置从[NSDatedate]检索到的当前date,然后将时间更改为上午10:00。

与所有的date操作一样,你必须使用NSDateComponents和NSCalendar

NSDate *now = [NSDate date]; NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier: NSCalendarIdentifierGregorian]; NSDateComponents *components = [calendar components:NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay fromDate:now]; [components setHour:10]; NSDate *today10am = [calendar dateFromComponents:components]; 

在iOS8中,Apple引入了一种方便的方法,可以节省几行代码:

 NSDate *d = [calendar dateBySettingHour:10 minute:0 second:0 ofDate:[NSDate date] options:0]; 

迅速:

 let calendar: NSCalendar! = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian) let now: NSDate! = NSDate() let date10h = calendar.dateBySettingHour(10, minute: 0, second: 0, ofDate: now, options: NSCalendarOptions.MatchFirst)! 

这个nsdate使用了不同的格式:

 NSDateFormatter *format = [[NSDateFormatter alloc] init]; [format setDateFormat:@"MMM dd, yyyy HH:mm"]; NSDate *now = [[NSDate alloc] init]; NSString *dateString = [format stringFromDate:now]; NSDateFormatter *inFormat = [[NSDateFormatter alloc] init]; [inFormat setDateFormat:@"MMM dd, yyyy"]; NSDate *parsed = [inFormat dateFromString:dateString]; 
 NSDate *currentDate = [NSDate date]; NSDateComponents *comps = [[NSDateComponents alloc] init]; [comps setHour:10]; NSDate *date = [gregorian dateByAddingComponents:comps toDate:currentDate options:0]; [comps release]; 

没有在xcode中testing:)

我只是设置与Matthias Bauch的时区答案而且它为我工作。 否则它会增加18:30分钟。

 let cal: NSCalendar = NSCalendar.currentCalendar() cal.timeZone = NSTimeZone(forSecondsFromGMT: 0) let newDate: NSDate = cal.dateBySettingHour(1, minute: 0, second: 0, ofDate: NSDate(), options: NSCalendarOptions())! 

您可以使用此方法进行任何分钟/小时/周期(又名am / pm)组合:

 - (NSDate *)todayModifiedWithHours:(NSString *)hours minutes:(NSString *)minutes andPeriod:(NSString *)period { NSDate *todayModified = NSDate.date; NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar]; NSDateComponents *components = [calendar components:NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit|NSMinuteCalendarUnit fromDate:todayModified]; [components setMinute:minutes.intValue]; int hour = 0; if ([period.uppercaseString isEqualToString:@"AM"]) { if (hours.intValue == 12) { hour = 0; } else { hour = hours.intValue; } } else if ([period.uppercaseString isEqualToString:@"PM"]) { if (hours.intValue != 12) { hour = hours.intValue + 12; } else { hour = 12; } } [components setHour:hour]; todayModified = [calendar dateFromComponents:components]; return todayModified; } 

请求示例:

 NSDate *todayAt10AM = [self todayModifiedWithHours:@"10" minutes:@"00" andPeriod:@"am"];