comparing time without date swift3

2019-08-18 03:50发布

问题:

I am using an API to get a list of times which is five times a day as string in (AM,PM) format without date,

("4:30 AM","1:00 PM","3:20: PM","6:40 PM","9:10 PM")

what I am trying to do is to show the next time in the screen depends on the current time on the iPhone

so if the time now is 5:00 PM the time should display on the screen is 6:40 PM

how can I compare times in swift without including the dates because I tried to convert the list of times I have to Date type but unfortunately am getting dates and the dates shows in 2001 so even if I try to compare the date would give me wrong result

 print(self._praytime.arraytime)




            for Dates in self._praytime.arraytime {
                let dateformatters = DateFormatter()
                dateformatters.dateStyle = .none
                dateformatters.timeStyle = .short
                let xxbbs = dateformatters.date(from: Dates)
                print(xxbbs!)
            }

after I got the times I put it in Array and I tried to execute the code upper so I can get the times without the date but what shows in the output screen was this

Optional(2000-01-01 11:14:00 +0000)
Optional(2000-01-01 20:06:00 +0000)
Optional(1999-12-31 23:57:00 +0000)
Optional(2000-01-01 03:11:00 +0000)
Optional(2000-01-01 04:41:00 +0000)

any idea how to solve this problem and if is there any other easy way to do this task I'm exciting to hear it

thank you all

回答1:

Suggestion using DateComponents

  • Assuming this given array

    let times = ["4:30 AM","1:00 PM","3:20 PM","6:40 PM","9:10 PM"]
    
  • Create a date formatter matching the format

    let formatter = DateFormatter()
    formatter.dateFormat = "h:mm a"
    
  • Map the time strings to Date and immediately to DateComponents considering only hour and minute

    let dateArray = times.map { Calendar.current.dateComponents([.hour, .minute], from:formatter.date(from:$0)!) }
    
  • Map this array to the next date from now matching the components respectively

    let upcomingDates = dateArray.map { Calendar.current.nextDate(after: Date(), matching: $0, matchingPolicy: .nextTime)!  }
    
  • Sort the array ascending, the first item is the date you are looking for

    let nextDate = upcomingDates.sorted().first!
    
  • Use the formatter to convert the date back to a time string

    print(formatter.string(from:nextDate))