1. 程式人生 > >NSDate 的一些操作(比較、建立、在現有date加減一定時間等)

NSDate 的一些操作(比較、建立、在現有date加減一定時間等)

建立當前時間

NSDate *date = [NSDate date];

從現在開始的24小時

        NSTimeInterval a_day = 24*60*60;

        NSDate *tomorrow = [NSDate dateWithTimeIntervalSinceNow:a_day];

根據已有日期建立日期

        NSTimeInterval a_day = 24*60*60;
        NSDate *date = [NSDate date];
        NSDate *tomorrow = [date addTimeInterval: date];

日期比較

        BOOL isEqual = [date isEqualToDate:tomorrow];
	if(isEqual){
		NSLog(@"equal");
	}

//獲取較早的日期

      NSDate *earlier_date = [tomorrow earlierDate:date];
        NSLog(@"earlierDate  = %@",earlierDate);

//較晚的日期

        NSDate *laterDate = [tomorrow laterDate:date];
        NSLog(@"laterDate  = %@",laterDate);

//兩個日期之間相隔多少秒

        NSTimeInterval secondsInterval= [date timeIntervalSinceDate:tomorrow];
        NSLog(@"secondsInterval=  %lf",secondsInterval);

//通過NSCalendar類來建立日期

        NSDateComponents *comps = [[NSDateComponentsalloc]init];
        [comps setMonth:01];
        [comps setDay:31];
        [comps setYear:2013];
        NSCalendar *calendar = [[NSCalendaralloc]initWithCalendarIdentifier:NSGregorianCalendar];
        NSDate *date = [calendar dateFromComponents:comps];

//從已有日期獲取日期

        unsigned units  = NSMonthCalendarUnit|NSDayCalendarUnit|NSYearCalendarUnit;
        NSDateComponents *_comps = [calendar components:units fromDate:date];
        NSInteger month = [_comps month];
        NSInteger year = [_comps year];
        NSInteger day = [_comps day];
        //NSDateFormatter實現日期的輸出
        NSDateFormatter *formatter = [[NSDateFormatteralloc]init];
        [formatter setDateStyle:NSDateFormatterFullStyle];//直接輸出的話是機器碼
        //或者是手動設定樣式[formatter setDateFormat:@"yyyy-mm-dd"];
        NSString *dateString = [formatter stringFromDate:date];
        NSLog(@"dateString = %@",dateString);
        NSLog(@"formater = %@",formatter);

//獲取日期格式物件

- (NSDateFormatter *)getDateFormatter {
	if (dateFormatter == nil) {
	dateFormatter = [[NSDateFormatter alloc] init];
	[dateFormatter setDateStyle:NSDateFormatterMediumStyle];
	[dateFormatter setTimeStyle:NSDateFormatterNoStyle];
	}
	return dateFormatter;
}