目录

NSDate基本用法

简单的记录一下关于时间的API和基本用法:

NSDate

1. 创建时间格式NSDateFormatter的格式约定

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
// 设置格式

hh : 12小时制

HH : 24小时制

mm : 

ss : 

yyyy : 

MM : 

dd : 

2. 从字符串获得时间 经过时间格式化对象 方法将字符串转变成NSDate

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
// 字符串转成时间
NSString *dateStr = @"2016-06-01 12:15";
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
formatter.dateFormat = @"yyyy-MM-dd hh:mm";

NSDate *date = [formatter dateFromString:dateStr];
NSLog(@"date = %@", date);

//打印结果
2016-06-01 12:27:55.386 DateTest[29095:4980284] date = 2016-05-31 16:15:00 +0000

3. 取出时间元素

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
// 获取当前时间
NSDate *now = [NSDate date];

// 创建日历对象
NSCalendar *calendar = [NSCalendar currentCalendar];

// 一次获取多个元素
NSCalendarUnit unit = NSCalendarUnitDay | NSCalendarUnitMonth | NSCalendarUnitYear;

NSDateComponents *cmps = [calendar components:unit fromDate:now];
NSLog(@"%zd-%zd-%zd", cmps.day, cmps.month,cmps.year);
//打印结果
2016-06-01 12:57:41.154 DateTest[29347:5093778] 1-6-2016

4. 时间比较(取出时间元素差)

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
// 两个时间
NSString *time1 = @"2016-05-01 12:12:20";
NSString *time2 = @"2016-06-01 12:12:20";

// 字符串转成时间
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
formatter.dateFormat = @"yyyy-MM-dd HH:mm:ss";

NSDate *date1 = [formatter dateFromString:time1];
NSDate *date2 = [formatter dateFromString:time2];

// 创建日历对象
NSCalendar *calender = [NSCalendar currentCalendar];

NSCalendarUnit unit= NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitHour| NSCalendarUnitMinute | NSCalendarUnitSecond;
// 比较时间差距
NSDateComponents *cmps = [calender components:unit fromDate:date1 toDate:date2 options:0];

NSLog(@"两个时间相差%zd年%zd月%zd日%zd小时%zd分%zd秒", cmps.year, cmps.month, cmps.day, cmps.hour, cmps.minute, cmps.second);

// 打印结果
2016-06-01 14:33:14.329 DateTest[29742:5306322] 两个时间相差0100小时00

5. 微博中欧美时间的转换(改变时区)

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
// Fri Oct 10 16:57:29 +0800 2014 , 欧美的时间格式
NSString *timeStr = @"Fri Oct 10 16:57:29 +0800 2014";
// 1.将服务器返回的时间格式化为NSDate
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
#warning 注意: 如果想再真机中转换时间, 除了要指定转换时间的格式以外, 还需要指定时间所在的时区, 如果不指定, 转换出来的时间有可能为null
formatter.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US"];
// 告诉时间格式化类, 怎样格式字符串
formatter.dateFormat = @"EEE MMM dd HH:mm:ss Z yyyy";

// 利用时间格式化类将字符串格式化为NSDate
NSDate *createdTime = [formatter dateFromString:timeStr];

6. NSDate和NSString之间的转换

1
2
- (NSString *)stringFromDate:(NSDate *)date;
- (NSDate *)dateFromString:(NSString *)string;

显示时分秒

1
2
3
4
5
6
/// 根据返回的数据换转成时分秒字符串
int time = 1465826169; // 时间戳
int hour = time / 3600;
int min = (time % 3600) / 60;
int second = time % 60;
NSString *timeStr = [NSString stringWithFormat:@"%2d : %2d : %2d", hour, min, second];