你如何比较Swift中Date的时间

时间:2017-01-14 03:33:53

标签: swift sorting date datetime time

我有两个日期对象:

1: 2017-01-13 11:40:17 +0000

2: 2016-03-15 10:22:14 +0000

我需要比较这些值的时间并忽略日期

示例:上午12:00和上午12:01,晚上12:01(上午12:01>上午12:00)== true

8 个答案:

答案 0 :(得分:9)

这是我最后采用的路线,这样可以轻松比较快速日期的时间

新对象时间:

class Time: Comparable, Equatable {
init(_ date: Date) {
    //get the current calender
    let calendar = Calendar.current

    //get just the minute and the hour of the day passed to it
    let dateComponents = calendar.dateComponents([.hour, .minute], from: date)

        //calculate the seconds since the beggining of the day for comparisions
        let dateSeconds = dateComponents.hour! * 3600 + dateComponents.minute! * 60

        //set the varibles
        secondsSinceBeginningOfDay = dateSeconds
        hour = dateComponents.hour!
        minute = dateComponents.minute!
    }

    init(_ hour: Int, _ minute: Int) {
        //calculate the seconds since the beggining of the day for comparisions
        let dateSeconds = hour * 3600 + minute * 60

        //set the varibles
        secondsSinceBeginningOfDay = dateSeconds
        self.hour = hour
        self.minute = minute
    }

    var hour : Int
    var minute: Int

    var date: Date {
        //get the current calender
        let calendar = Calendar.current

        //create a new date components.
        var dateComponents = DateComponents()

        dateComponents.hour = hour
        dateComponents.minute = minute

        return calendar.date(byAdding: dateComponents, to: Date())!
    }

    /// the number or seconds since the beggining of the day, this is used for comparisions
    private let secondsSinceBeginningOfDay: Int

    //comparisions so you can compare times
    static func == (lhs: Time, rhs: Time) -> Bool {
        return lhs.secondsSinceBeginningOfDay == rhs.secondsSinceBeginningOfDay
    }

    static func < (lhs: Time, rhs: Time) -> Bool {
        return lhs.secondsSinceBeginningOfDay < rhs.secondsSinceBeginningOfDay
    }

    static func <= (lhs: Time, rhs: Time) -> Bool {
        return lhs.secondsSinceBeginningOfDay <= rhs.secondsSinceBeginningOfDay
    }


    static func >= (lhs: Time, rhs: Time) -> Bool {
        return lhs.secondsSinceBeginningOfDay >= rhs.secondsSinceBeginningOfDay
    }


    static func > (lhs: Time, rhs: Time) -> Bool {
        return lhs.secondsSinceBeginningOfDay > rhs.secondsSinceBeginningOfDay
    }
}

日期扩展,方便访问:     //增加了从日期中获取时间的能力:

extension Date {
    var time: Time {
        return Time(self)
    }
}

示例:

let firstDate = Date()
let secondDate = firstDate

//Will return true
let timeEqual = firstDate.time == secondDate.time

答案 1 :(得分:7)

我的方法是使用Calendar在同一天制作Date个对象,然后使用例如timeIntervalSinceReferenceDate进行比较。

另一个更干净(但最有可能产生更多代码的行)是为名为Date的{​​{1}}创建扩展名,然后比较生成的双倍值。

基于第二种方法的示例:

secondsFromBeginningOfTheDay() -> TimeInterval

答案 2 :(得分:5)

我这样做有问题,如果您只是想比较两个日期的时间,我想我找到了一个更简单的解决方案。它确实感觉有点&#34; hacky&#34;但似乎运作良好。

SWIFT 4

// date1 and date2 are the dates you want to compare

let calendar = Calendar.current

var newDate = Date(TimeIntervalSinceReferenceDate: 0) // Initiates date at 2001-01-01 00:00:00 +0000
var newDate1 = Date(TimeIntervalSinceReferenceDate: 0) // Same as above

// Recieving the components from the dates you want to compare 
let newDateComponents = calendar.dateComponents([.hour, .minute], from: date1)!
let newDate1Components = calendar.dateComponents([.hour, .minute], from: date2)!

// Adding those components
newDate = calendar.date(byAdding: newDateComponents, to: newDate)
newDate1 = calendar.date(byAdding: newDate1Components, to: newDate1)

答案 3 :(得分:4)

我的解决方案是在忽略日期的情况下比较两天的时间:

let date1 = some time as a date
let date2 = some other time as a date

let time1 = 60*Calendar.current.component(.hour, from: date1!) + Calendar.current.component(.minute, from: date1!)
let time2 =  60*Calendar.current.component(.hour, from: date2!) + Calendar.current.component(.minute, from: date2!)

现在你可以比较整数time1和time2而不考虑当天。如果需要更高的精度,可以添加秒数/秒。

答案 4 :(得分:2)

一天中没有标准类型。一个合理的类型只是一个元组:

typealias TimeOfDay = (hour: Int, minute: Int, second: Int)

要创建这些TimeOfDay值,您需要Calendar。默认情况下,Calendar使用设备的系统范围时区。如果您不想这样做,请明确设置Calendar的时区。例如:

var calendar = Calendar.autoupdatingCurrent
calendar.timeZone = TimeZone(abbreviation: "UTC")!

现在,您可以使用DateFormatter将字符串转换为Date s(如有必要),然后使用calendar从{{1}中提取时间组件}} S:

Date

最后,您可以比较这些let strings: [String] = ["2017-01-13 11:40:17 +0000", "2016-03-15 10:22:14 +0000"] let parser = DateFormatter() parser.dateFormat = "yyyy-MM-dd HH:mm:ss Z" let timesOfDay: [TimeOfDay] = strings.map({ (string) -> TimeOfDay in let components = calendar.dateComponents([.hour, .minute, .second], from: parser.date(from: string)!) return (hour: components.hour!, minute: components.minute!, second: components.second!) }) Swift.print(timesOfDay) // Output: [(11, 40, 17), (10, 22, 14)] 值。 Swift附带了元素为TimeOfDay的元组的标准比较运算符,因此这个Comparable类型符合条件。你可以这样说:

TimeOfDay

答案 5 :(得分:2)

假设我们有两个字符串格式的日期:

// "2017-01-13 11:40:17 +0000"
// "2016-03-15 10:22:14 +0000"

我们需要将此字符串转换为Date格式,我们创建DateFormatter()并设置要转换的格式(“ yyyy-MM-dd''HH:mm:ssZ”)

//date formatter converts string to date in our case
let firstDateFormatter = DateFormatter()
firstDateFormatter.dateFormat = "yyyy-MM-dd' 'HH:mm:ssZ"

现在我们可以将日期从字符串转换为日期格式

   //convert string to dates
    if let date1 = firstDateFormatter.date(from: "2017-01-13 09:40:17 +0000"),
        let date2 = firstDateFormatter.date(from: "2016-03-15 10:22:14 +0000") {
    

我们想要的只是比较小时和分钟。因此,将dateformat更改为“ HH:mm”

//we ve got the dates, now switch dateformat for other job
firstDateFormatter.dateFormat = "HH:mm"

现在从我们的日期获取字符串值,该字符串值仅包含“ HH:mm”

   // convert date to string ( part of string we want to compare )
        let HHmmDate1 = firstDateFormatter.string(from: date1) //"17:40"
        let HHmmDate2 = firstDateFormatter.string(from: date2) //"18:22"

最后一步是从“ HH:mm”值中获取日期,假设我们要求DateFormatter仅在时间上给我们一个日期,在我们的例子中是“ 17:40”和“ 18:22”。 DateFormatter将为日期添加一些值,因此我们两个日期都会自动获得2000年1月1日,但是它将获得我们提供的时间。

   //produce "default" dates with desired HH:mm
    //default means same date, but time is different
        let HH1 = firstDateFormatter.date(from: HHmmDate1) //"Jan 1, 2000 at 5:40 PM"
        let HH2 = firstDateFormatter.date(from: HHmmDate2) //"Jan 1, 2000 at 6:22 PM"

现在我们可以轻松比较日期了

 //compare
        HH1! > HH2!
}

还有很多选项可以将日期与日历进行比较

答案 6 :(得分:1)

如果您使用Swifter Swift

,这在Swift中非常简单
date1.day = 1
date1.month = 1
date1.year = 2000

date2.day = 1
date2.month = 1
date2.year = 2000

现在您可以在date1和date2上使用>,<,==运算符来仅比较时间分量。

编辑-您可以通过扩展日期类来做到这一点,例如swifter-swift可以满足日期组件的需求。

public var day: Int {
        get {
            return Calendar.current.component(.day, from: self)
        }
        set {
            let allowedRange = Calendar.current.range(of: .day, in: .month, for: self)!
            guard allowedRange.contains(newValue) else { return }

            let currentDay = Calendar.current.component(.day, from: self)
            let daysToAdd = newValue - currentDay
            if let date = Calendar.current.date(byAdding: .day, value: daysToAdd, to: self) {
                self = date
            }
        }
    } 

答案 7 :(得分:1)

此代码有效,可以在操场上轻松检查

let s1 = "22:31"
let s2 = "14:31"
let f = DateFormatter()
f.dateFormat = "HH:mm"

f.date(from: s1)! //"Jan 1, 2000 at 10:31 PM"
f.date(from: s2)! //"Jan 1, 2000 at 2:31 PM"
f.date(from: s1)! > f.date(from: s2)!  // true