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

你可能感兴趣的文章
no available service ‘default‘ found, please make sure registry config corre seata
查看>>
No compiler is provided in this environment. Perhaps you are running on a JRE rather than a JDK?
查看>>
no connection could be made because the target machine actively refused it.问题解决
查看>>
No Datastore Session bound to thread, and configuration does not allow creation of non-transactional
查看>>
No fallbackFactory instance of type class com.ruoyi---SpringCloud Alibaba_若依微服务框架改造---工作笔记005
查看>>
No Feign Client for loadBalancing defined. Did you forget to include spring-cloud-starter-loadbalanc
查看>>
No mapping found for HTTP request with URI [/...] in DispatcherServlet with name ...的解决方法
查看>>
No mapping found for HTTP request with URI [/logout.do] in DispatcherServlet with name 'springmvc'
查看>>
No module named 'crispy_forms'等使用pycharm开发
查看>>
No module named 'pandads'
查看>>
No module named cv2
查看>>
No module named tensorboard.main在安装tensorboardX的时候遇到的问题
查看>>
No module named ‘MySQLdb‘错误解决No module named ‘MySQLdb‘错误解决
查看>>
No new migrations found. Your system is up-to-date.
查看>>
No qualifying bean of type XXX found for dependency XXX.
查看>>
No qualifying bean of type ‘com.netflix.discovery.AbstractDiscoveryClientOptionalArgs<?>‘ available
查看>>
No resource identifier found for attribute 'srcCompat' in package的解决办法
查看>>
no session found for current thread
查看>>
No static resource favicon.ico.
查看>>
no such file or directory AndroidManifest.xml
查看>>