1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
|
#import <Foundation/Foundation.h>
int
main(
int
argc,
const
char
* argv[])
{
@autoreleasepool {
//1.创建NSDate对象
//通过date创建对象拿到的是0时区的时刻,本地的时刻还需加8个小时
NSDate *date1 = [NSDate date];
NSLog(@
"%@"
, date1);
//2.创建一个NSDate对象,让它表示明天此时的时刻
//从当前时刻开始,加上给定的时间间隔
//NSTimeInterval 是一个时间间隔,时间间隔是以秒为单位的
NSDate *date2 = [NSDate dateWithTimeIntervalSinceNow:24 * 60 * 60];
NSLog(@
"%@"
, date2);
//3.创建NSDate对象,表示昨天此时的时刻
NSDate *date3 = [NSDate dateWithTimeIntervalSinceNow:- 24 * 60 * 60];
NSLog(@
"%@"
, date3);
//4.获得两个指定时刻的时间间隔NSTimeInterval
NSTimeInterval interval1 = [date2 timeIntervalSinceDate:date3];
NSLog(@
"%.2f"
, interval1 / 24 / 60 /60);
//5.输出日期格式
//创建一个日期格式类的对象
NSDateFormatter *formatter1 = [[NSDateFormatter alloc] init];
//设置日期的格式
//设置当前时区
[formatter1 setTimeZone:[NSTimeZone localTimeZone]];
//月用大写的MM,小时大写HH表示24小时制
// [formatter1 setDateFormat:@"yyyy年MM月dd日 hh:mm:ss"];
//(1)设置日期的风格,日期的样式
[formatter1 setDateStyle:NSDateFormatterFullStyle];
//(2)设置时间的风格,时间的样式
[formatter1 setTimeStyle:NSDateFormatterLongStyle];
//将日期转为字符串
NSString *dateString1 = [formatter1 stringFromDate:date1];
NSLog(@
"%@"
, dateString1);
//6.通过时间间隔初始化NSDate对象
//获得当前时间和1970.1.1时间间隔
NSDate *date5 = [NSDate dateWithTimeIntervalSince1970:0];
NSTimeInterval interval2 = [date1 timeIntervalSinceDate:date5];
NSLog(@
"%.2f"
, interval2 / 365 / 24 / 60 / 60);
//根据时间间隔以及给定的1970.1.1获得指定的时间
NSDate *date4 = [NSDate dateWithTimeInterval:interval2 sinceDate:date5];
NSLog(@
"%@"
, date4);
//创建日期格式对象
NSDateFormatter *formatter3 = [[NSDateFormatter alloc] init];
//设置转化的日期格式,一定要和给定的日期字符串格式相同
[formatter3 setDateFormat:@
"yyyy年MM月dd日 HH点mm分ss秒"
];
//将日期格式串按照日期格式转化为NSDate对象
NSDate *date6 = [formatter3 dateFromString:@
"2014年05月01日 10点23分24秒"
];
NSLog(@
"%@"
, date6);
}
return
0;
}
|
NSDate类的常用方法
最新推荐文章于 2018-11-06 15:48:02 发布