// 当前时间创建NSDate
NSDate *myDate = [NSDate date];
NSLog(@"myDate = %@",myDate);
//从现在开始的24小时
NSTimeInterval secondsPerDay = 24*60*60;
NSDate *tomorrow = [NSDate dateWithTimeIntervalSinceNow:secondsPerDay];
NSLog(@"tomorrow = %@",tomorrow);
//根据已有日期创建日期
NSTimeInterval secondsPerDay1 = 24*60*60;
NSDate *now = [NSDate date];
NSDate *yesterDay = [now dateByAddingTimeInterval:-secondsPerDay1];
NSLog(@"yesterDay = %@",yesterDay);
//比较日期
BOOL sameDate = [now isEqualToDate:yesterDay];
NSLog(@"sameDate = %hhd",sameDate);
//获取较早的日期
NSDate *earlierDate = [yesterDay earlierDate:now];
NSLog(@"earlierDate = %@",earlierDate);
//获取较晚的日期
NSDate *laterDate = [yesterDay laterDate:now];
NSLog(@"laterDate = %@",laterDate);
//两个日期之间相隔多少秒
NSTimeInterval secondsBetweenDates= [yesterDay timeIntervalSinceDate:now];
NSLog(@"secondsBetweenDates= %lf",secondsBetweenDates);
//通过NSCalendar类来创建日期
NSDateComponents *comp = [[NSDateComponents alloc]init];
[comp setMonth:06];
[comp setDay:12];
[comp setYear:2015];
NSCalendar *myCal= [[NSCalendar alloc]initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
NSDate *myDate1 = [myCal dateFromComponents:comp];
NSLog(@"myDate1 = %@",myDate1);
//从已有日期获取日期
unsigned units = NSCalendarUnitMonth|NSCalendarUnitDay|NSCalendarUnitYear;
NSDateComponents *comp1 = [myCal components:units fromDate:now];
NSInteger month = [comp1 month];
NSInteger year = [comp1 year];
NSInteger day = [comp1 day];
//NSDateFormatter实现日期的输出
NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
[formatter setDateStyle:NSDateFormatterFullStyle];//直接输出的话是机器码
//或者是手动设置样式[formatter setDateFormat:@"yyyy-mm-dd"];
NSString *string = [formatter stringFromDate:now];
NSLog(@"string = %@",string);
NSLog(@"formater = %@",formatter);
//用NSCalendar实现,计算某个时间C是某个日期B是相应时期A,中的第几(Hour?Day?Month?)
NSCalendar *cal = [NSCalendar currentCalendar];
NSLog(@"My calendar is %@",[cal calendarIdentifier]);//获取日期格式对象
unsigned long daymonth = [cal ordinalityOfUnit:NSCalendarUnitDay//时间B(天)
inUnit:NSCalendarUnitMonth//时间A(月)
forDate:now];//时间C(当前时间)
NSLog(@"This is day %lu of the month",daymonth);//当前时间C,是一个月(A)的第几天(B)
网友评论