[OC Foundation框架 - 15] NSDate

日期处理类

  1. 定义
  2. 时间间隔计算
  3. 时间比较,返回其一
  4. 时间格式化
 1 void dateCreate()
 2 {
 3     //date return current time
 4     NSDate *date = [NSDate date];
 5     NSLog(@"%@", date);
 6    
 7     //+ 10 sec
 8     date = [NSDate dateWithTimeIntervalSinceNow:10];
 9     NSLog(@"%@", date);
10    
11     //1970-1-1 00:00:00 + 10 sec
12     date = [NSDate dateWithTimeIntervalSince1970:10];
13     NSLog(@"%@", date);
14    
15     //Random future time?
16     date = [NSDate distantFuture];
17     NSLog(@"%@", date);
18    
19     date = [NSDate distantPast];
20     NSLog(@"%@", date);
21 }
22  
23 void dateUse()
24 {
25     NSDate *date = [NSDate date];
26     //NSTimeInterval is double
27     NSTimeInterval i = [date timeIntervalSince1970];
28     NSLog(@"%f", i);
29 }
30  
31 void dateFormat()
32 {
33     NSDate *date = [NSDate date];
34     NSDateFormatter *f = [[NSDateFormatter alloc] init];
35     f.dateFormat = @"yyyy-MMM-dd HH:mm:ss";
36     NSString *s = [f stringFromDate:date];
37     NSLog(@"1:%@", s);
38    
39     NSDate *d2 = [f dateFromString:@"2014-7月-29 22:12:12"];
40     NSLog(@"2:%@",d2);
41 }
 
字符串、日期格式转换:
1         // 17.将2013年05月05日转换为2013-05-05
2         NSMutableString *str17 = @"2013年05月05日";
3         NSDateFormatter *dateFormatter1 = [[NSDateFormatter alloc] init];
4         dateFormatter1.dateFormat = @"yyyy年MM月dd日";
5         NSDate *date1 = [dateFormatter1 dateFromString:str17];
6         NSDateFormatter *dateFormatter2 = [[NSDateFormatter alloc] init];
7         dateFormatter2.dateFormat = @"yyyy-MM-dd";
8         NSString *str17_2 = [dateFormatter2 stringFromDate:date1];
9         NSLog(@"题目17, 转换后的日期是%@", str17_2);
 
posted @ 2014-11-24 19:17  HelloVoidWorld  阅读(246)  评论(0编辑  收藏  举报