首页 > 代码库 > NSDate(NSCalendar,NSDateComponents,NSDateFormatter)
NSDate(NSCalendar,NSDateComponents,NSDateFormatter)
-1 NSString 转成 NSDate
NSString *time = @"2014-05-18 09:24:40"; NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; dateFormatter.dateFormat = @"yyyy-MM-dd HH:mm:ss"; NSDate *date = [dateFormatter dateFromString:time]; NSLog(@"%@",date);
-2 获取本地时间 (将格林威治时间转换成本地时间)
NSDate *date = [NSDate date]; NSTimeZone *zone = [NSTimeZone systemTimeZone]; NSInteger interval = [zone secondsFromGMTForDate:date]; NSDate *localeDate = [date dateByAddingTimeInterval:interval]; NSLog(@"%@",localeDate);
-3 将 NSDate 转成 NSString
NSDate *date = [NSDate date]; NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; dateFormatter.dateFormat = @"yyyy-MM-dd HH:mm:ss Z";//"Z"表示时区 NSString *currentDate = [dateFormatter stringFromDate:date]; NSLog(@"%@",currentDate);
使用 NSDateFormatter 会自动将时间转换成本地时间输出
-4 使用 NSCalendar 和 NSDateComponents 获取时间要素
NSDate *date = [NSDate date]; NSCalendar *calendar = [NSCalendar currentCalendar]; int unit = NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond; NSDateComponents *dateComponents = [calendar components:unit fromDate:date]; NSLog(@"现在时间是%li年%li月%li天%li小时%li分钟%li秒", dateComponents.year, dateComponents.month, dateComponents.day, dateComponents.hour, dateComponents.minute, dateComponents.second);
-5 比较两个时间的时间差(这里以格林威治时间和本地时间做示例)
NSDate *date = [NSDate date]; NSTimeZone *zone = [NSTimeZone systemTimeZone]; NSInteger interval = [zone secondsFromGMTForDate:date]; NSDate *localeDate = [date dateByAddingTimeInterval:interval]; NSCalendar *calendar = [NSCalendar currentCalendar]; int unit = NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond; NSDateComponents *dateComponents = [calendar components:unit fromDate:date toDate:localeDate options:0]; NSLog(@"格林威治时间和本地时间相差%ld年%ld月%ld天%ld小时%ld分钟%ld秒", dateComponents.year, dateComponents.month, dateComponents.day, dateComponents.hour, dateComponents.minute, dateComponents.second);
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。