【Swift】日期比较函数 记录下 Comparing date in Swift

Add this code to your project and comparing dates is easier than ever

扩展NSDATE

//swift 3.0.2

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
extension NSDate
{
    func isGreaterThanDate(dateToCompare : NSDate) -> Bool
    {
        var isGreater = false
        if self.compare(dateToCompare as Date) == ComparisonResult.orderedDescending
        { isGreater = true }
        return isGreater
    }
     
    func isLessThanDate(dateToCompare : NSDate) -> Bool
    {
        var isLess = false
        if self.compare(dateToCompare as Date) == ComparisonResult.orderedAscending
        { isLess = true }
        return isLess
    }
     
    func addDays(daysToAdd : Int) -> NSDate
    {
        let secondsInDays : TimeInterval = Double(daysToAdd) * 60 * 60 * 24
        let dateWithDaysAdded : NSDate = self.addingTimeInterval(secondsInDays)
        return dateWithDaysAdded
    }
     
    func addHours(hoursToAdd : Int) -> NSDate
    {
        let secondsInHours : TimeInterval = Double(hoursToAdd) * 60 * 60
        let dateWithHoursAdded : NSDate = self.addingTimeInterval(secondsInHours)
        return dateWithHoursAdded
    }
}

 

t’s easy to use. Here’s a couple of examples

在.SWIFT调用就行了,EASY的很!

 

1
2
3
4
5
6
var today = NSDate()
var oneHourFromNow = today.addHours(1)
if today.isGreaterThanDate(oneHourFromNow) {
  println("Something is terrebly wrong.")
}
var aWeekFromNow = today.addDays(7)

 

原文链接:http://myxcode.net/2015/08/30/comparing-dates-in-swift/

 

posted @   布袋  阅读(512)  评论(0编辑  收藏  举报
编辑推荐:
· .NET 原生驾驭 AI 新基建实战系列:向量数据库的应用与畅想
· 从问题排查到源码分析:ActiveMQ消费端频繁日志刷屏的秘密
· 一次Java后端服务间歇性响应慢的问题排查记录
· dotnet 源代码生成器分析器入门
· ASP.NET Core 模型验证消息的本地化新姿势
阅读排行:
· ThreeJs-16智慧城市项目(重磅以及未来发展ai)
· .NET 原生驾驭 AI 新基建实战系列(一):向量数据库的应用与畅想
· Ai满嘴顺口溜,想考研?浪费我几个小时
· Browser-use 详细介绍&使用文档
· 软件产品开发中常见的10个问题及处理方法
点击右上角即可分享
微信分享提示