iOS NSDate、NSCalendar、NSDateComponents
2024-08-31 10:07:51
时间解析(NSDate、NSCalendar、NSDateComponents):
1、使用NSCalendar和NSDateComponents解析日期,直接获取到年月日时分秒。获取到年月日时分秒其实都是通过NSDateComponents来解析的
[calendar components:(NSCalendarUnitYear |NSCalendarUnitMonth | NSCalendarUnitDay) fromDate:date];
NSDate *date = [NSDate date]; NSCalendar *calendar = [NSCalendar currentCalendar]; NSDateComponents *comps; // 年月日获得
comps = [calendar components:(NSCalendarUnitYear |NSCalendarUnitMonth | NSCalendarUnitDay) fromDate:date]; NSInteger y = [comps year]; NSInteger m = [comps month]; NSInteger d = [comps day]; NSLog(@"year: %ld month: %ld, day: %ld", y, m, d);
//当前的时分秒获得 comps = [calendar components:(NSCalendarUnitHour |NSCalendarUnitMinute | NSCalendarUnitSecond) fromDate:date]; NSInteger h = [comps hour]; NSInteger m = [comps minute]; NSInteger s = [comps second]; NSLog(@"hour: %li minute: %li second: %li", h, m,s);
2、还可以使用NSDateFormatter将日期格式化为 "yyyy-MM-dd hh/HH:mm:ss" 后,再用字符串逐步切割,逐渐获取到年月日时分秒(先用" "切割,然后再用”-“和”:"切割)即可获取到
NSDate *date = [NSDate date]; NSDateFormatter *formatter= [[NSDateFormatteralloc] init]; formatter.dateFormat =@"yyyy-MM-dd HH:mm:ss"; NSString *str = [formatterstringFromDate:date]; NSArray *arr = [str componentsSeparatedByString:@" "]; NSArray *arr1 = [arr[0] componentsSeparatedByString:@"-"]; // 年 月 日 NSArray *arr2 = [arr[1] componentsSeparatedByString:@":"]; // 时 分 秒
最新文章
- maven 打war包tomcat服务器乱码问题
- MFC 单文档消息执行顺序。
- vs2012 MSDN帮助文档离线包下载安装方法
- Hibernate常见问题
- 查看oracle数据库中的保留字
- leetcode 110 Balanced Binary Tree ----- java
- Uva 1588 Kickdown
- HW5.21
- 学习XAML中的一些基本语法
- ANDROID_MARS学习笔记_S05_002_给传感器注册listener
- Spring+AOP+Log4j 用注解的方式记录指定某个方法的日志
- hdu4085
- USACO5.4-Character Recognition
- APP测试常用工具以及框架
- 队列queue实现线程的消费者和生产者
- poj 1151 (未完成) 扫描线 线段树 离散化
- maven配置多仓库镜像(转)
- react-navigation实现页面框架(转载)
- AttributeError: 'WebElement' object has no attribute 'send_keys'
- Redis 在线管理工具(phpRedisAdmin)介绍
热门文章
- SecureCRT rz 上传文件失败问题
- MongoDB的学习--文档的查询
- IP Failover Setup using Keepalived on CentOS/Redhat 6
- C# 通过Get、Post、Soap调用WebService的方法
- String-------RegularHelper
- cart中回归树的原理和实现
- nodejs+express+jade+mongodb给我baby做个小相册(2)-留言板
- Use the PDFs below or the HTML contents to the left to install and configure P6 EPPM and its additional components.
- 重构13天 抽取方法对象(Extract Method Object)
- 适用于jquery1.11.1的ajaxfileupload.js