iOS 控制元件之 UIDatePicker

征途LN發表於2014-02-20

這是一個日期選擇器

建立並設定一個日期選擇器

    _datePicker = [[UIDatePicker alloc]initWithFrame:CGRectMake(20, 30, 0, 0)];
    _datePicker.datePickerMode = UIDatePickerModeDate;
    [_datePicker addTarget:self action:@selector(datePickerChanged:) forControlEvents:UIControlEventValueChanged];
    NSLocale * local = [NSLocale systemLocale];
    _datePicker.locale = local;
    NSCalendar * calendar = [NSCalendar autoupdatingCurrentCalendar];
    _datePicker.calendar =calendar;
    NSTimeZone * zone = [NSTimeZone systemTimeZone];
    _datePicker.timeZone = zone;
    NSDate * dater = [NSDate date];
    //設定預設顯示的最小日期
    _datePicker.date =dater;
    _datePicker.minimumDate =[dater earlierDate:[NSDate dateWithTimeIntervalSince1970:99999 ]];
    //設定最大日期
    _datePicker.maximumDate = [dater laterDate:[NSDate dateWithTimeInterval:999999 sinceDate:[NSDate date]]];
    [self.view addSubview:_datePicker];
繫結事件
-(void)datePickerChanged:(UIDatePicker*)pocker{
    [pocker setDate:pocker.date animated:YES];
    NSDateFormatter * dateFormatter = [[NSDateFormatter alloc]init];
    [dateFormatter setDateStyle:NSDateFormatterFullStyle];
    NSString * stringDate = [dateFormatter stringFromDate:pocker.date];
    NSLog(@"\ndate-->%@\n",stringDate);
    NSArray * dateArray = [stringDate componentsSeparatedByString:@","];
    NSArray * month = [[dateArray objectAtIndex:1]componentsSeparatedByString:@" "];
    
    NSLog(@"星期是:%@\n",[dateArray objectAtIndex:0]);
    NSLog(@"月份是:%@\n",[month objectAtIndex:1]);
    NSLog(@"日  是:%@\n",[month objectAtIndex:2]);
    NSLog(@"年份是:%@\n",[dateArray objectAtIndex:2]);
    
}

控制檯輸出:


date-->Tuesday, March 4, 2014
2014-02-20 17:32:38.836 ControlDemo[2237:70b] 星期是:Tuesday
2014-02-20 17:32:38.837 ControlDemo[2237:70b] 月份是:March
2014-02-20 17:32:38.837 ControlDemo[2237:70b] 日  是:4
2014-02-20 17:32:38.837 ControlDemo[2237:70b] 年份是: 2014






            

相關文章