本文主要是介绍17,Objective-C Foundation框架中的NSDate,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
获取时间、考虑时区、时间格式
- (void)viewDidLoad
{[super viewDidLoad];// Do any additional setup after loading the view, typically from a nib.//获取当前时间NSDate *now = [NSDate date];NSLog(@"It's %@ now,",now);//获取距离某个时间点的时间NSDate *then = [[NSDate alloc] initWithTimeInterval:3600 sinceDate:now];NSLog(@"after 3600 second:%@",then);//考虑时区NSTimeZone *zone = [NSTimeZone systemTimeZone];NSInteger interval = [zone secondsFromGMTForDate:now];NSDate *localDate = [now dateByAddingTimeInterval:interval];NSLog(@"the local date is %@",localDate);//时间格式NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];[dateFormatter setDateFormat:@"年月日 YYYY/mm/dd 时间 hh:mm:ss"]; //设置时间格式NSString *dateString = [dateFormatter stringFromDate:[NSDate date]];NSLog(@"dateString = %@",dateString);[dateFormatter setDateFormat:@"YYYY-MM-dd"];NSString *date = [dateFormatter stringFromDate:[NSDate date]];NSLog(@"年月日 date = %@",date);[dateFormatter setDateFormat:@"hh:mm:ss"];NSString *time = [dateFormatter stringFromDate:[NSDate date]];NSLog(@"时间 time = %@",time);
}
日期的比较
03 | NSDate *currentDate = [NSDate date]; |
06 | NSDate *laterDate = [[NSDate alloc] initWithTimeInterval:60*60 sinceDate:[NSDate date]]; |
09 | NSDate *earlierDate = [[NSDate alloc] initWithTimeInterval:-60*60 sinceDate:[NSDate date]]; |
12 | if ([currentDate laterDate:laterDate]) { |
14 | NSLog(@ "current-%@比later-%@晚" ,currentDate,laterDate); |
18 | if ([currentDate earlierDate:earlierDate]) { |
20 | NSLog(@ "current-%@ 比 earlier-%@ 早" ,currentDate,earlierDate); |
23 | if ([currentDate compare:earlierDate]==NSOrderedDescending) { |
27 | if ([currentDate compare:currentDate]==NSOrderedSame) { |
31 | if ([currentDate compare:laterDate]==NSOrderedAscending) { |
这篇关于17,Objective-C Foundation框架中的NSDate的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!