根據(jù)當(dāng)前日期獲取一個月以后的日期
-(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;
}
給一個時間苗傅,給一個數(shù)针余,正數(shù)是以后n個月萄焦,負數(shù)是前n個月;
NSDate時間換算
@interfaceViewController?()
@end
@implementationViewController
-?(void)viewDidLoad?{
[superviewDidLoad];
//?1尾序、獲取當(dāng)前時間
NSDate*now?=?[NSDatedate];
NSDateFormatter*nowFormate?=?[[NSDateFormatteralloc]init];
nowFormate.dateFormat=@"yyyy-MM-dd?HH:mm:ss";
NSString*nowTime?=?[nowFormatestringFromDate:now];
NSLog(@"nowTime?=?%@",nowTime);
//?2、拿現(xiàn)在的時間和過去時間或者將來時間對比盼铁,計算出相差多少天仗阅,多少年,多少秒等等重归;
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(@"相差世紀個數(shù)?=?%ld",[compsEraera]);
NSLog(@"相差年個數(shù)?=?%ld",[compsYearyear]);
NSLog(@"相差月個數(shù)?=?%ld",[compsMonthmonth]);
NSLog(@"相差小時個數(shù)?=?%ld",[compsHourhour]);
NSLog(@"相差分鐘個數(shù)?=?%ld",[compsMinuteminute]);
NSLog(@"相差秒個數(shù)?=?%ld",[compsSecondsecond]);
//?3米愿、獲取時間戳(相對于1970年)
CGFloat?timestamp?=?now.timeIntervalSince1970;
NSLog(@"距離1970年有多少秒?=?%f",timestamp);
//?4、計算距離現(xiàn)在有多少秒
CGFloat?sinceNow?=?beforTime.timeIntervalSinceNow;
NSLog(@"距離現(xiàn)在有多少秒?=?%f",fabs(sinceNow));
}
@end
輸出結(jié)果:
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]相差世紀個數(shù)= 0
2016-06-14 16:46:12.654 Timer[2811:639641]相差年個數(shù)= 1
2016-06-14 16:46:12.654 Timer[2811:639641]相差月個數(shù)= 23
2016-06-14 16:46:12.654 Timer[2811:639641]相差小時個數(shù)= 17541
2016-06-14 16:46:12.654 Timer[2811:639641]相差分鐘個數(shù)= 1052481
2016-06-14 16:46:12.654 Timer[2811:639641]相差秒個數(shù)= 63148872
2016-06-14 16:46:12.654 Timer[2811:639641]距離1970年有多少秒= 1465893972.649262
2016-06-14 16:46:12.654 Timer[2811:639641]距離現(xiàn)在有多少秒= 63148872.654635
如果轉(zhuǎn)載請注明轉(zhuǎn)于:AirZilong的博客