3

我有一个日期选择器和 2 个按钮。当我单击按钮时,我想以编程方式设置 datepicker 值。就像当我按下第一个按钮时,日期选择器值变成今天的日期和 00:00:00: 时间,当我按下第二个按钮时,日期选择器值变成今天的日期和 23:59:59 时间。

怎么做?

4

3 回答 3

11

简单的任务,假设您已经添加了两个在按钮按下时调用的函数,您需要这样的东西:

-(IBAction)beginPressed:(id)sender
{
  NSDate * now = [[NSDate alloc] init];
  NSCalendar *cal = [NSCalendar currentCalendar];
  NSDateComponents * comps = [cal components:NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit fromDate:now];
  [comps setHour:0];
  [comps setMinute:0];
  [comps setSecond:0];
  NSDate * date = [cal dateFromComponents:comps];
  [self.datePicker setDate:date animated:TRUE];

}
-(IBAction)endPressed:(id)sender
{
  NSDate * now = [[NSDate alloc] init];
  NSCalendar *cal = [NSCalendar currentCalendar];
  NSDateComponents * comps = [cal components:NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit fromDate:now];
  [comps setHour:23];
  [comps setMinute:59];
  [comps setSecond:59];
  NSDate * date = [cal dateFromComponents:comps];
  [self.datePicker setDate:date animated:TRUE];
}

我认为设置组件的部分对您来说并不清楚,检查上述类的API,您会发现更多。

编辑:我将日历更改为当前的默认日历并用现在初始化日历。

于 2012-10-28T07:58:36.370 回答
2
NSDateFormatter *dateFormat;
  dateFormat = [[NSDateFormatter alloc] init];
 [dateFormat setDateFormat:@"h:mm a"];
  NSDate *exampleDateFromString =[dateFormat dateFromString:@"8:48 AM"]; 
  date-picker.minimumDate=exampleDateFromString;
 [date-picker setDate:exampleDateFromString];
于 2014-09-23T06:57:33.753 回答
2

对于那些想知道如何在 Swift 中做到这一点的人:

let now = NSDate()
let cal = NSCalendar.currentCalendar()
let comp = cal.components([.Year, .Month, .Day], fromDate: now)
comp.hour = 0 // or whatever you need
comp.minute = 0
let date = cal.dateFromComponents(comp)!
picker.setDate(date, animated: true)
于 2016-07-11T16:53:51.567 回答