如何重设从[NSDate date]检索到的当前日期,然后将时间更改为上午10:00。
如何重设从[NSDate date]检索到的当前日期,然后将时间更改为上午10:00。
Answers:
与所有日期操作一样,您必须使用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中测试:)
您可以将这种方法用于任何分钟/小时/时间段(又名上午/下午)组合:
- (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"];