天天看點

iOS NSDate 時間計算

//聯系人:石虎  QQ: 1224614774 昵稱:嗡嘛呢叭咪哄

列印效果:

iOS NSDate 時間計算

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad

{

    [super viewDidLoad];

    //目前時間

    [self currentTime];

    //當年共多少天

    [self yearTotalDays];

    //相差幾天

    [self quiteFewDays];

}

- (void)currentTime

{

    //得到目前的時間

    NSDate * date = [NSDate date];

    //時間管理

    NSDateFormatter * dateFormatter = [[NSDateFormatter alloc] init];

    //時間格式

    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];

    //設定時間間隔(秒)(這個我是計算出來的,不知道有沒有簡便的方法 )

    NSTimeInterval time = 365 * 24 * 60 * 60;//一年的秒數

    //得到一年之前的目前時間(-:表示向前的時間間隔(即去年),如果沒有,則表示向後的時間間隔(即明年))

    NSDate * lastYear = [date dateByAddingTimeInterval:-time];

    //轉化為字元串

    NSString * startDate = [dateFormatter stringFromDate:lastYear];

    NSString *dayYY = [NSString stringWithFormat:@"%@",startDate];

    NSLog(@"dayYY---> %@",dayYY);

}

- (void)yearTotalDays

{

    //2.當年共多少天

    NSCalendar *calender = [NSCalendar currentCalendar];

    //計算時間

    NSDateComponents *comps =[calender components:(NSYearCalendarUnit | NSMonthCalendarUnit |NSDayCalendarUnit | NSWeekCalendarUnit)fromDate:[NSDate date]];

    int count = 0;

    for (int i=1; i<=12; i++) {

        [comps setMonth:i];

        NSRange range = [calender rangeOfUnit:NSDayCalendarUnit inUnit:NSMonthCalendarUnit forDate: [calender dateFromComponents:comps]];

        count += range.length;

    }

    NSLog(@"count--->%d", count);

}

- (void)quiteFewDays

{

    //3.當時時間距離未來(過去)的天數

    NSString * time = @"2017-06-07";  //可以寫過去時間差

    NSDateFormatter * dateFormatter = [[NSDateFormatter alloc] init];

    [dateFormatter setDateFormat:@"yyyy-MM-dd"];

    //根據需求 選擇date的方法

    NSDate * date = [dateFormatter dateFromString:time];//x現在到未來的時間差

    //NSDate * date = [time dateFromString:dateFormatter];//現在和以前的時間差天數

    NSDate * currentDate = [NSDate date];

    NSUInteger sec = [date timeIntervalSinceDate:currentDate];

    NSLog(@"sec---->%zd",sec/(3600*24));

}