您的位置:首页 > 移动开发 > Objective-C

Objective-C学习之 NSDate简单使用说明

2013-08-28 09:46 267 查看
一、NSDate初始化

01
//
获取当前日期
02
NSDate
*date = [NSDate date];
03
 
04
//
打印结果: 当前时间 date = 2013-08-16 09:00:04 +0000
05
NSLog(@
"当前时间
date = %@"
,date);
06
 
07
//
获取从某个日期开始往前或者往后多久的日期,此处60代表60秒,如果需要获取之前的,将60改为-60即可
08
date
= [[NSDate alloc] initWithTimeInterval:60 sinceDate:[NSDate date]];
09
 
10
//打印结果:当前时间
往后60s的时间date = 2013-08-16 09:01:04 +0000
11
NSLog(@
"当前时间
往后60s的时间date = %@"
,date);
PS:测试时时间是下午5点,但是得到的当前时间却是上午9点,相差了8小时,是时区的问题

解决办法:

1
NSTimeZone
*zone = [NSTimeZone systemTimeZone];
2
 
3
NSInteger
interval = [zone secondsFromGMTForDate: date];
4
 
5
NSDate
*localDate = [date  dateByAddingTimeInterval: interval];
6
 
7
//
打印结果 正确当前时间 localDate = 2013-08-16 17:01:04 +0000
8
NSLog(@
"正确当前时间
localDate = %@"
,localDate);
二、NSDate与NSString的转换

01
/*----
NSDate与NSString----*/
02
NSDateFormatter
*dateFormatter =[[NSDateFormatter alloc] init];
03
 
04
//
设置日期格式
05
[dateFormatter
setDateFormat:@
"年月日
YYYY/mm/dd 时间 hh:mm:ss"
];
06
 
07
NSString
*dateString = [dateFormatter stringFromDate:[NSDate date]];
08
 
09
//
打印结果:dateString = 年月日 2013/10/16 时间 05:15:43
10
NSLog(@
"dateString
= %@"
,dateString);
11
 
12
 
13
//
设置日期格式
14
[dateFormatter
setDateFormat:@
"YYYY-MM-dd"
];
15
 
16
NSString
*year = [dateFormatter stringFromDate:[NSDate date]];
17
 
18
//
打印结果:年月日 year = 2013-08-16
19
NSLog(@
"年月日
year = %@"
,year);
20
 
21
//
设置时间格式
22
[dateFormatter
setDateFormat:@
"hh:mm:ss"
];
23
 
24
NSString
*
time
=
[dateFormatter stringFromDate:[NSDate date]];
25
 
26
//
打印结果:时间 time = 05:15:43
27
NSLog(@
"时间
time = %@"
,
time
);
三、日期的比较

01
/*----日期时间的比较----*/
02
//
当前时间
03
NSDate
*currentDate = [NSDate date];
04
 
05
//
比当前时间晚一个小时的时间
06
NSDate
*laterDate = [[NSDate alloc] initWithTimeInterval:60*60 sinceDate:[NSDate date]];
07
 
08
//
比当前时间早一个小时的时间
09
NSDate
*earlierDate = [[NSDate alloc] initWithTimeInterval:-60*60 sinceDate:[NSDate date]];
10
 
11
//
比较哪个时间迟
12
if
([currentDate
laterDate:laterDate]) {
13
    
//
打印结果:current-2013-08-16 09:25:54 +0000比later-2013-08-16 10:25:54 +0000晚
14
    
NSLog(@
"current-%@比later-%@晚"
,currentDate,laterDate);
15
}
16
 
17
//
比较哪个时间早
18
if
([currentDate
earlierDate:earlierDate]) {
19
    
//
打印结果:current-2013-08-16 09:25:54 +0000 比 earlier-2013-08-16 08:25:54 +0000
20
    
NSLog(@
"current-%@
比 earlier-%@ 早"
,currentDate,earlierDate);
21
}
22
 
23
if
([currentDate
compare:earlierDate]==NSOrderedDescending) {
24
    
//
打印结果
25
    
NSLog(@
"current
晚"
);
26
}
27
if
([currentDate
compare:currentDate]==NSOrderedSame) {
28
    
//
打印结果
29
    
NSLog(@
"时间相等"
);
30
}
31
if
([currentDate
compare:laterDate]==NSOrderedAscending) {
32
    
//
打印结果
33
    
NSLog(@
"current
早"
);
34
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  NSDate