博客
关于我
使用Swift操作NSDate类型基础
阅读量:437 次
发布时间:2019-03-06

本文共 1113 字,大约阅读时间需要 3 分钟。

  时间类型是我们在处理业务的时候使用非常频繁的一个数据类型。下面我们看一下时间NSDate的基本使用方法。

1.比较大小

  我比较擅长.NET,我们知道C#里面DateTime类型可以使用">""<""="来直接判断。但是在Swift里NSDate是不支持这种比较的方式的。我们需要使用NSDate.Compare方法来比较。NSDate.Compare返回一个枚举NSComparisonResult。这个枚举包含3个值:

NSComparisonResult.OrderedAscending//时间升序

NSComparisonResult.OrderedSame//相同

NSComparisonResult.OrderedDescending//时间倒序

 

 

其中NSDate()默认返回现在时间。所以date2的时间值肯定比date1大。如果想要实现C#里使用">""<""="来比较时间的话,可以使用以上方法重载操作符。

2.计算时间差

  我们知道在C#里可以直接对DateTime类型进行减法运算,得到的结果是一个时间差。那么在Swift里如何进行呢。我们使用

NSCalendar.currentCalendar().components来的到2个时间之间间隔的时间。该方法返回一个NSDateComponents类型的对象。NSDateComponents对象表示一段时间,且使用我们更易于读取的方式来描述:

func diff(from:NSDate,to:NSDate)->NSDateComponents{        let mostUnits: NSCalendarUnit = .YearCalendarUnit | .MonthCalendarUnit | .DayCalendarUnit | .HourCalendarUnit | .MinuteCalendarUnit | .SecondCalendarUnit    let components = NSCalendar.currentCalendar().components(mostUnits,fromDate:from, toDate:to, options:nil)        return components;}

 

3.构造时间

   有时候我们需要自己构造一个时间。其实就是上面的datePare方法。我们可以指定年月日来构造一个NSDateComponents,然后使用NSCalendar.dateFromComponents方法来构造一个时间。

 

  以上差不多就是NSDate在Swift里最基本的用法。

转载地址:http://sldyz.baihongyu.com/

你可能感兴趣的文章
MySQL 8.0开始Group by不再排序
查看>>
mysql ansi nulls_SET ANSI_NULLS ON SET QUOTED_IDENTIFIER ON 什么意思
查看>>
multi swiper bug solution
查看>>
MySQL Binlog 日志监听与 Spring 集成实战
查看>>
MySQL binlog三种模式
查看>>
multi-angle cosine and sines
查看>>
Mysql Can't connect to MySQL server
查看>>
mysql case when 乱码_Mysql CASE WHEN 用法
查看>>
Multicast1
查看>>
mysql client library_MySQL数据库之zabbix3.x安装出现“configure: error: Not found mysqlclient library”的解决办法...
查看>>
MySQL Cluster 7.0.36 发布
查看>>
Multimodal Unsupervised Image-to-Image Translation多通道无监督图像翻译
查看>>
MySQL Cluster与MGR集群实战
查看>>
multipart/form-data与application/octet-stream的区别、application/x-www-form-urlencoded
查看>>
mysql cmake 报错,MySQL云服务器应用及cmake报错解决办法
查看>>
Multiple websites on single instance of IIS
查看>>
mysql CONCAT()函数拼接有NULL
查看>>
multiprocessing.Manager 嵌套共享对象不适用于队列
查看>>
multiprocessing.pool.map 和带有两个参数的函数
查看>>
MYSQL CONCAT函数
查看>>