NSDate使用筆記

weixin_34148340發表於2016-07-13

字串 ----> NSDate

NSString *dateStr = @"2016-07-13 14:24:11";
//建立一個時間戳
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
dateFormatter.dateFormat = @"yyyy-MM-dd HH:mm:ss";
NSDate *date = [dateFormatter dateFromString:dateStr];
//設定時區
NSTimeZone *zone = [NSTimeZone systemTimeZone];
NSInteger interval = [zone secondsFromGMTForDate: date];
date = [date  dateByAddingTimeInterval: interval];
NSLog(@"date == %@", date);

//===========================

NSString* string = @"Wed, 05 May 2011 10:50:00 +0800";
NSDateFormatter *inputFormatter = [[NSDateFormatter alloc] init];
[inputFormatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"en_US"]];
[inputFormatter setDateFormat:@"EEE, d MMM yyyy HH:mm:ss Z"];
date = [inputFormatter dateFromString:string];
zone = [NSTimeZone systemTimeZone];
interval = [zone secondsFromGMTForDate: date];
date = [date  dateByAddingTimeInterval: interval];
NSLog(@"date = %@", date);

2.NSDate ----> 字串

date = [NSDate date];
dateFormatter.dateFormat = @"yyyy-MM-dd W HH:mm:ss";
string = [dateFormatter stringFromDate:date];
NSLog(@"%@", string);

3.時間比較和計算
.....

4.獲取0點時間

date = [NSDate date];
dateFormatter.dateFormat = @"yyyy-MM-dd W HH:mm:ss";
string = [dateFormatter stringFromDate:date];
NSLog(@"%@", string);

相關文章