NSDate:时间的获取和操作
1、获取当前时间
1 //获取当前日期2 NSDate *date = sender.date;3 NSLog(@"%@",date);
2、将date转换为字符串并格式化
1 //date转字符串2 NSDateFormatter *formatter = [[NSDateFormatter alloc]init];3 //YYYY:年 MM:月 dd:日 HH:24小时制 hh:12小时制4 formatter.dateFormat = @"YYYY-MM-dd HH:mm:ss";5 NSString *strdate = [formatter stringFromDate:date];6 NSLog(@"%@",strdate);
3、将字符串转回date
1 //字符串转date2 NSDate *date2 = [formatter dateFromString:strdate];3 NSLog(@"%@",date2);
4、将字符串日期分解为年、月、日
1 //将日期分解为年月日2 NSCalendar *calendar = [NSCalendar currentCalendar];3 NSInteger unitflags = NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay;4 NSDateComponents *components = [calendar components:unitflags fromDate:date];5 NSLog(@"year:%ld month:%ld day:%ld",[components year],[components month],[components day]);
5、将年、月、日合并为日期字符串
1 //将年月日组合成日期2 [components setYear:2014];3 [components setMonth:9];4 [components setDay:1];5 NSDate *date3 = [calendar dateFromComponents:components];6 NSLog(@"%@",date3);