博客
关于我
使用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/

你可能感兴趣的文章
node exporter完整版
查看>>
node HelloWorld入门篇
查看>>
Node JS: < 一> 初识Node JS
查看>>
Node JS: < 二> Node JS例子解析
查看>>
Node Sass does not yet support your current environment: Linux 64-bit with Unsupported runtime(93)解决
查看>>
Node Sass does not yet support your current environment: Windows 64-bit with Unsupported runtime(72)
查看>>
Node 裁切图片的方法
查看>>
node+express+mysql 实现登陆注册
查看>>
Node+Express连接mysql实现增删改查
查看>>
node, nvm, npm,pnpm,以前简单的前端环境为什么越来越复杂
查看>>
Node-RED中Button按钮组件和TextInput文字输入组件的使用
查看>>
vue3+Ts 项目打包时报错 ‘reactive‘is declared but its value is never read.及解决方法
查看>>
Node-RED中Slider滑杆和Numeric数值输入组件的使用
查看>>
Node-RED中Switch开关和Dropdown选择组件的使用
查看>>
Node-RED中使用exec节点实现调用外部exe程序
查看>>
Node-RED中使用function函式节点实现数值计算(相加计算)
查看>>
Node-RED中使用html节点爬取HTML网页资料之爬取Node-RED的最新版本
查看>>
Node-RED中使用JSON数据建立web网站
查看>>
Node-RED中使用json节点解析JSON数据
查看>>