How do you compare just the time of a Date in Swift?

后端 未结 8 949
挽巷
挽巷 2020-12-29 10:05

I have two Date Objects:

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

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

I need to compare

8条回答
  •  -上瘾入骨i
    2020-12-29 10:51

    Let say we got two dates in string format:

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

    We need to convert this strings to Date format, we create DateFormatter() and set the format ("yyyy-MM-dd' 'HH:mm:ssZ") it gonna convert

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

    Now we can get our date from string to Date format

       //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") {
        
    

    What we want is to compare only Hours and Minutes. So change dateformat to "HH:mm"

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

    Now get the string value from our date, that only contain "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"
    

    Final step is to get date from our "HH:mm" values, let say we ask DateFormatter to give us a date, based on time only, in our case "17:40" and "18:22". DateFormatter will put some values for dates, so we get Jan 1, 2000 automatically for both dates, but it will get the time we provide.

       //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"
    

    Now we could easily compare dates

     //compare
            HH1! > HH2!
    }
    

    There are many options to compare dates with Calendar also

提交回复
热议问题