startTime = 10:00 AM endTime = 01:00 PM
Now i want to split the time in the interval of 30mins like
10:00 AM 10:30 AM 11:00 AM 11:30 AM .......... till 01:00 PM.
I tried like
let startDate : NSDate! = NSDate() let time1 : NSDate = startDate.dateByAddingTimeInterval((60*60)/2) let time2 : NSDate = time1.dateByAddingTimeInterval((60*60)/2) let time3 : NSDate = time2.dateByAddingTimeInterval((60*60)/2) let time4 : NSDate = time3.dateByAddingTimeInterval((60*60)/2)
func makeTimeInterval(startTime:String ,endTime:String) -> String
{
let timeFormat = DateFormatter()
timeFormat.dateFormat = "hh:mm a"
var fromTime:NSDate = (timeFormat.date(from:startTime) as NSDate?)!
let toTime:NSDate = (timeFormat.date(from:endTime) as NSDate?)!
var dateByAddingThirtyMinute : NSDate!
let timeinterval : TimeInterval = toTime.timeIntervalSince(fromTime as Date)
let numberOfIntervals : Double = timeinterval / 3600;
var formattedDateString : String!
for _ in stride(from: 0, to: Int(numberOfIntervals * 2), by: 1)
{
dateByAddingThirtyMinute = fromTime.addingTimeInterval(1800)
fromTime = dateByAddingThirtyMinute
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "hh:mm a"
formattedDateString = dateFormatter.string(from: dateByAddingThirtyMinute! as Date) as String?
print("Time after 30 min = \(formattedDateString)")
}
return formattedDateString
}
Tried those things and i got like 10:10,10:40..etc how to make 30 min round of interval like 10:00,10:30...etc
Thanks in advance
Use the below function if user enters anytime less than 30 than it will start with very next 30 min e.g 10:20, start from 10:30. And if user give time greater than 30 then very time will be 00 e.g 10:45, start from 11:00.
func makeTimeInterval(startTime:String ,endTime:String) -> String
{
var arr = startTime.components(separatedBy: " ")[0].components(separatedBy: ":")
let str = arr[1] as String
if (Int(str)! > 0 && Int(str)! < 30){
arr[1] = "00"
}
else if(Int(str)! > 30){
arr[1] = "30"
}
let startT:String = "\(arr.joined(separator: ":")) \(startTime.components(separatedBy: " ")[1])"
let timeFormat = DateFormatter()
timeFormat.dateFormat = "hh:mm a"
var fromTime:NSDate = (timeFormat.date(from:startT) as NSDate?)!
let toTime:NSDate = (timeFormat.date(from:endTime) as NSDate?)!
var dateByAddingThirtyMinute : NSDate!
let timeinterval : TimeInterval = toTime.timeIntervalSince(fromTime as Date)
let numberOfIntervals : Double = timeinterval / 3600;
var formattedDateString : String!
for _ in stride(from: 0, to: Int(numberOfIntervals * 2), by: 1)
{
dateByAddingThirtyMinute = fromTime.addingTimeInterval(1800)
fromTime = dateByAddingThirtyMinute
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "hh:mm a"
formattedDateString = dateFormatter.string(from: dateByAddingThirtyMinute! as Date) as String?
print("Time after 30 min = \(formattedDateString)")
}
return formattedDateString
}