NSDate简单用法

- (void)viewDidLoad {

    [super viewDidLoad];

    //获取当前时间

    NSDate *now=[NSDate date];

    NSLog(@"now:%@",now);//now:2016-01-26 03:03:21 +0000

    

    //转换成当地时间,解决时差问题

    NSDate *localNow=[self changeToLocalDate:now];

    NSLog(@"localNow:%@",localNow);//localNow:2016-01-26 11:03:21 +0000

    

    //NSDate转NSString(不用考虑时差问题)

    NSString *strNow=[self stringFromDate:now format:@"yyyy-MM-dd HH:mm:ss"];

    NSLog(@"strNow:%@",strNow);//strNow:2016-01-26 11:03:21

    

    //NSString转NSDate(方法1)

    NSString *str1=strNow;

    NSDate *date1=[self dateFromString:str1 format:@"yyyy-MM-dd HH:mm:ss"];

    NSLog(@"date1:%@",date1);//date1:2016-01-26 11:03:21 +0000

    //NSString转NSDate(方法2)

    NSDate *date2=[self dateFromStringNew:[NSString stringWithFormat:@"%@ z",str1] format:@"yyyy-MM-dd HH:mm:ss z"];

    NSLog(@"date2:%@",date2);//date2:2016-01-26 11:03:21 +0000

}

//NSString转NSDate(方法1)

-(NSDate *)dateFromString:(NSString *)string format:(NSString *)format{

    NSTimeZone *timeZone = [NSTimeZone timeZoneWithAbbreviation:@"GMT"];//或UTC

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

    [dateFormatter setTimeZone:timeZone];

    [dateFormatter setDateFormat:format];

    NSDate *date=[dateFormatter dateFromString:string];

    return date;

}

//NSString转NSDate(方法2)

-(NSDate *)dateFromStringNew:(NSString *)string format:(NSString *)format{

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

    [dateFormatter setDateFormat:format];

    NSDate *date=[dateFormatter dateFromString:string];

    return date;

}

//NSDate转NSString(不用考虑时差问题)

-(NSString *)stringFromDate:(NSDate *)date format:(NSString *)format{

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

    [dateFormatter setDateFormat:format];

    NSString *dateString = [dateFormatter stringFromDate:date];

    return dateString;

}

//转换成当地时间,解决时差问题

-(NSDate *)changeToLocalDate:(NSDate *)date{

    NSTimeZone *zone = [NSTimeZone systemTimeZone];

    NSInteger interval = [zone secondsFromGMTForDate: date];

    NSDate *localDate = [date  dateByAddingTimeInterval: interval];

    return localDate;

}

//日期之间比较可用以下方法

/*

- (BOOL)isEqualToDate:(NSDate *)otherDate;

与otherDate比较,相同返回YES

- (NSDate *)earlierDate:(NSDate *)anotherDate;

与anotherDate比较,返回较早的那个日期

- (NSDate *)laterDate:(NSDate *)anotherDate;

与anotherDate比较,返回较晚的那个日期

- (NSComparisonResult)compare:(NSDate *)other;

该方法用于排序时调用:

. 当实例保存的日期值与anotherDate相同时返回NSOrderedSame

. 当实例保存的日期值晚于anotherDate时返回NSOrderedDescending

. 当实例保存的日期值早于anotherDate时返回NSOrderedAscending

*/

你可能感兴趣的:(NSDate简单用法)