for example:- startDate:- 20-08-2018 10:00 AM endDate:- 20-08-2018 02:30 PM
Output:- ["10:00 AM", "10:30 AM", "11:00 AM", "11:30 AM", "12:00PM", "12:30 PM", "01:00 PM", "01:30 PM", "02:00 PM", "02:30 PM"]
var fromTime:Date = getFromTime fromTime = fromTime.addingTimeInterval(-1800)
guard let toTime:Date = timeFormat.date(from:endTime) else {
return nil
}
var dateByAddingThirtyMinute : Date!
let timeinterval : TimeInterval = toTime.timeIntervalSince(fromTime)
let numberOfIntervals : Double = timeinterval / 3600;
var timeArrayAM = [String]()
var timeArrayPM = [String]()
for _ in stride(from: 0, to: Int(numberOfIntervals * 2), by: 1) {
dateByAddingThirtyMinute = fromTime.addingTimeInterval(1800)
fromTime = dateByAddingThirtyMinute
if let dateString = dateByAddingThirtyMinute.format(with: "hh:mm a") as? String {
// print("Time after 30 min = \(dateString)")
if temp == 0 {
let time = dateString
guard let getStopTime = timeFormat.date(from: time) else {
return nil
}
var stopTime = getStopTime
var date = Date()
date = date.addingTimeInterval(TimeInterval(advanceTimeInterval*60))
let calendar = Calendar.current
let year = calendar.component(.year, from: date)
let month = calendar.component(.month, from: date)
let day = calendar.component(.day, from: date)
let hour = calendar.component(.hour, from: stopTime)
let minute = calendar.component(.minute, from: stopTime)
stopTime = calendar.date(bySetting: .year, value: year, of: stopTime)!
stopTime = calendar.date(bySetting: .month, value: month, of: stopTime)!
stopTime = calendar.date(bySetting: .day, value: day, of: stopTime)!
stopTime = calendar.date(bySetting: .hour, value: hour, of: stopTime)!
stopTime = calendar.date(bySetting: .minute, value: minute, of: stopTime)!
let timeDifference = calendar.dateComponents([.hour, .minute], from: stopTime, to: date)
// print_debug("************************************")
// print(timeDifference.hour, timeDifference.minute)
if timeDifference.hour! < 0 || timeDifference.minute! < 0 || (timeDifference.hour! == 0 && timeDifference.minute! == 0 ) {
showFirstTime = dateString
temp = 1
}
// print_debug("************************************")
}
You can do this,
Output of above is,