1 // 當(dāng)前時(shí)間創(chuàng)建NSDate
NSDate *myDate = [NSDate date];
NSLog(@"myDate = %@",myDate);
2 //從現(xiàn)在開(kāi)始的24小時(shí)
NSTimeInterval secondsPerDay = 24*60*60;
NSDate *tomorrow = [NSDate dateWithTimeIntervalSinceNow:secondsPerDay];
NSLog(@"myDate = %@",tomorrow);
3//根據(jù)已有日期創(chuàng)建日期
NSTimeInterval secondsPerDay1 = 24*60*60;
NSDate *now = [NSDate date];
NSDate *yesterDay = [now addTimeInterval:-secondsPerDay1];
NSLog(@"yesterDay = %@",yesterDay);
4//比較日期
BOOL sameDate = [now isEqualToDate:yesterDay];
NSLog(@"sameDate = %lu",sameDate);
4.1//獲取較早的日期
NSDate *earlierDate = [yesterDay earlierDate:now];
NSLog(@"earlierDate? = %@",earlierDate);
4.2//較晚的日期
NSDate *laterDate = [yesterDay laterDate:now];
NSLog(@"laterDate? = %@",laterDate);
//兩個(gè)日期之間相隔多少秒
NSTimeInterval secondsBetweenDates= [yesterDay timeIntervalSinceDate:now];
NSLog(@"secondsBetweenDates=? %lf",secondsBetweenDates);
//通過(guò)NSCALENDAR類(lèi)來(lái)創(chuàng)建日期
NSDateComponents *comp = [[NSDateComponentsalloc]init];
[comp setMonth:06];
[comp setDay:01];
[comp setYear:2001];
NSCalendar *myCal = [[NSCalendaralloc]initWithCalendarIdentifier:NSGregorianCalendar];
NSDate *myDate1 = [myCal dateFromComponents:comp];
NSLog(@"myDate1 = %@",myDate1);
//從已有日期獲取日期
unsigned units? = NSMonthCalendarUnit|NSDayCalendarUnit|NSYearCalendarUnit;
NSDateComponents *comp1 = [myCal components:units fromDate:now];
NSInteger month = [comp1 month];
NSInteger year = [comp1 year];
NSInteger day = [comp1 day];
//NSDateFormatter實(shí)現(xiàn)日期的輸出
NSDateFormatter *formatter = [[NSDateFormatteralloc]init];
[formatter setDateStyle:NSDateFormatterFullStyle];//直接輸出的話是機(jī)器碼
//或者是手動(dòng)設(shè)置樣式[formatter setDateFormat:@"yyyy-mm-dd"];
NSString *string = [formatter stringFromDate:now];
NSLog(@"string = %@",string);
NSLog(@"formater = %@",formatter);
//獲取日期格式對(duì)象
- (NSDateFormatter *)dateFormatter {
if (dateFormatter == nil) {
dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateStyle:NSDateFormatterMediumStyle];
[dateFormatter setTimeStyle:NSDateFormatterNoStyle];
}
return dateFormatter;
}