根据当前日期获取一个月以后的日期
-(NSDate*)getPriousorLaterDateFromDate:(NSDate*)date withMonth:(int)month
{
NSDateComponents*comps = [[NSDateComponents alloc] init];
[comps setMonth:month];
NSCalendar*calender = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDate*mDate = [calender dateByAddingComponents:comps toDate:date options:0];
return mDate;
}
给一个时间,给一个数,正数是以后n个月,负数是前n个月;
NSDate时间换算
@interfaceViewController ()
@end
@implementationViewController
- (void)viewDidLoad {
[superviewDidLoad];
// 1、获取当前时间
NSDate*now = [NSDatedate];
NSDateFormatter*nowFormate = [[NSDateFormatteralloc]init];
nowFormate.dateFormat=@"yyyy-MM-dd HH:mm:ss";
NSString*nowTime = [nowFormatestringFromDate:now];
NSLog(@"nowTime = %@",nowTime);
// 2、拿现在的时间和过去时间或者将来时间对比,计算出相差多少天,多少年,多少秒等等;
NSDate*beforTime = [nowFormatedateFromString:@"2014-06-14 19:25:00"];
NSCalendar*calender = [[NSCalendaralloc]initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
//世纪
NSInteger era = kCFCalendarUnitEra;
//年
NSInteger year = kCFCalendarUnitYear;
//月
NSInteger month = kCFCalendarUnitMonth;
//小时
NSInteger hour = kCFCalendarUnitHour;
//分钟
NSInteger minute = kCFCalendarUnitMinute;
//秒
NSInteger second = kCFCalendarUnitSecond;
NSDateComponents*compsEra = [calendercomponents:erafromDate:beforTimetoDate:nowoptions:0];
NSDateComponents*compsYear = [calendercomponents:yearfromDate:beforTimetoDate:nowoptions:0];
NSDateComponents*compsMonth = [calendercomponents:monthfromDate:beforTimetoDate:nowoptions:0];
NSDateComponents*compsHour = [calendercomponents:hourfromDate:beforTimetoDate:nowoptions:0];
NSDateComponents*compsMinute = [calendercomponents:minutefromDate:beforTimetoDate:nowoptions:0];
NSDateComponents*compsSecond = [calendercomponents:secondfromDate:beforTimetoDate:nowoptions:0];
NSLog(@"相差世纪个数 = %ld",[compsEraera]);
NSLog(@"相差年个数 = %ld",[compsYearyear]);
NSLog(@"相差月个数 = %ld",[compsMonthmonth]);
NSLog(@"相差小时个数 = %ld",[compsHourhour]);
NSLog(@"相差分钟个数 = %ld",[compsMinuteminute]);
NSLog(@"相差秒个数 = %ld",[compsSecondsecond]);
// 3、获取时间戳(相对于1970年)
CGFloat timestamp = now.timeIntervalSince1970;
NSLog(@"距离1970年有多少秒 = %f",timestamp);
// 4、计算距离现在有多少秒
CGFloat sinceNow = beforTime.timeIntervalSinceNow;
NSLog(@"距离现在有多少秒 = %f",fabs(sinceNow));
}
@end
输出结果:
2016-06-14 16:46:12.651 Timer[2811:639641] nowTime = 2016-06-14 16:46:12
2016-06-14 16:46:12.654 Timer[2811:639641]相差世纪个数= 0
2016-06-14 16:46:12.654 Timer[2811:639641]相差年个数= 1
2016-06-14 16:46:12.654 Timer[2811:639641]相差月个数= 23
2016-06-14 16:46:12.654 Timer[2811:639641]相差小时个数= 17541
2016-06-14 16:46:12.654 Timer[2811:639641]相差分钟个数= 1052481
2016-06-14 16:46:12.654 Timer[2811:639641]相差秒个数= 63148872
2016-06-14 16:46:12.654 Timer[2811:639641]距离1970年有多少秒= 1465893972.649262
2016-06-14 16:46:12.654 Timer[2811:639641]距离现在有多少秒= 63148872.654635
如果转载请注明转于:AirZilong的博客