iOS关于时间:NSDate

获取当前时间: 

NSDate *localDate = [NSDate date];

获取UIDatePicker的时间:

NSDate *pickerDate = [self.datePicker date];

NSDate格式转换为NSString格式:

- (NSString*)getSelectedDateStr{

NSDate *pickerDate = [self.datePicker date];  // 获取用户通过UIDatePicker设置的日期和时间

NSDateFormatter*formatter = [[NSDateFormatteralloc]init];  // 创建一个日期格式器

[formattersetDateFormat:@"yyyy-MM-dd HH:mm:ss"];

return  [formatterstringFromDate:self.datePicker.date];

}

NSString格式转换为NSDate格式:

- (NSDate *)getDateAction{

NSString *birthdayStr=@"2010-08-04 16:01:03";

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];

[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];

[dateFormatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:8]];//解决8小时时间差问题

NSDate *date = [dateFormatter dateFromString:birthdayStr];

NSLog(@"*****%@",date);

return date;

}

UIDatePicker设置最值:

- (void)viewDidLoad {

[super viewDidLoad];

self.view.backgroundColor = [UIColor orangeColor];

self.datePicker = [[UIDatePicker alloc]initWithFrame:CGRectMake(0, 80, self.view.frame.size.width, 216)];

self.datePicker.backgroundColor = [UIColor groupTableViewBackgroundColor];

[self.view addSubview:self.datePicker];

[self.datePicker addTarget:self action:@selector(dateChanged:) forControlEvents:UIControlEventValueChanged ];//重点:UIControlEventValueChanged

//设置显示格式

//默认根据手机本地设置显示为中文还是其他语言

NSLocale *locale = [[NSLocale alloc] initWithLocaleIdentifier:@"zh_CN"];//设置为中文显示

self.datePicker.locale = locale;

//当前时间创建NSDate

NSDate *localDate = [NSDate date];

//在当前时间加上的时间:格里高利历

NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];

NSDateComponents *offsetComponents = [[NSDateComponents alloc] init];

//设置时间

[offsetComponents setYear:0];

[offsetComponents setMonth:0];

[offsetComponents setDay:5];// 当前时间最多推后5天

[offsetComponents setHour:20];// 最多推后20小时

[offsetComponents setMinute:0];

[offsetComponents setSecond:0];

//设置最大值时间

NSDate *maxDate = [gregorian dateByAddingComponents:offsetComponents toDate:localDate options:0];

//设置属性

self.datePicker.minimumDate = localDate;

self.datePicker.maximumDate = maxDate;

}


UIDatePicker响应事件的实现:

- (void)dateChanged:(id)sender{

UIDatePicker *control = (UIDatePicker*)sender;

NSDate* date = control.date;

//添加你自己响应代码

NSLog(@"dateChanged响应事件:%@",date);

//NSDate格式转换为NSString格式

NSString *dateString = [self getSelectedDateStr];

//打印显示日期时间

NSLog(@"格式化显示时间:%@",dateString);

}

日期比较:

/**

NSComparisonResult的取值

NSOrderedAscending // 升序, 越往右边越大

NSOrderedSame,  // 相等

NSOrderedDescending // 降序, 越往右边越小

*/

NSComparisonResult result =  [aDate compare:bDate];

if (result == NSOrderedAscending) { // 升序, 越往右边越大

NSLog(@"bDate > aDate");

} else if (result == NSOrderedDescending) { // 降序, 越往右边越小

NSLog(@"aDate > bDate");

} else {

NSLog(@"aDate == bDate");

}

你可能感兴趣的:(iOS关于时间:NSDate)