在Objective C中为UIDatePicker设置自定义日期和时间

时间:2016-03-02 07:41:43

标签: objective-c nsdate uidatepicker

我必须将自定义日期和时间设置为UIDatePicker 最短日期:当前日期时间, 最长日期:直到明天晚上。

例如: 今天是3月2日,最长日期应该是3月3日晚上11:59

我试过了:

-(NSDate *) getTomorrowDate {

    NSDateComponents *dayComponent = [[NSDateComponents alloc] init];
    dayComponent.day = 1;
    dayComponent.hour = 23;
    dayComponent.minute = 59;
    NSCalendar *theCalendar = [NSCalendar currentCalendar];
    NSDate *nextDate = [theCalendar dateByAddingComponents:dayComponent toDate:[NSDate date:[NSDate date] withFormat:@"yyyy-MM-dd hh:mm:ss"] options:0];

    return nextDate;
}

但是3月4日也回来了,请好好纠正我!

谢谢。

1 个答案:

答案 0 :(得分:1)

这是一个增加两天的解决方案,剥离时间部分并减去一秒。

- (NSDate *)getTomorrowDate {
  NSCalendar *calendar = [NSCalendar currentCalendar];
  // add two days
  NSDate *dayAfterTomorrow = [calendar dateByAddingUnit:NSCalendarUnitDay value:2 toDate:[NSDate date] options:0];
  // get start of the day
  NSDate *startOfDayAfterTomorrow = [calendar startOfDayForDate:dayAfterTomorrow];
  // subtract one second.
  return [calendar dateByAddingUnit:NSCalendarUnitSecond value:-1 toDate:startOfDayAfterTomorrow options:0];
}