如何在 swift 2.3 中设置 30 分钟的时间间隔

How to make 30 minute time intervals in swift 2.3

开始时间 = 10:00 上午 结束时间 = 01:00 下午

现在我想把时间分成30分钟的间隔,比如

10:00 上午 10:30 上午 11:00 上午 11:30 上午 .......直到 01:00 下午.

我试过了

   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

        }

尝试了这些东西,我得到了 10:10,10:40..etc 如何像 10:00,10:30...等

一样进行 30 分钟的循环

提前致谢

您可以使用 NSDateComponents class。 class 允许获取一些日期单位。您可以从日期中获取分钟和小时值,并将分钟四舍五入到最接近的 "good" 值(有时您也应该更改小时数)。
之后,您可以获得具有新的小时和分钟值的新日期。 不要忘记时区。

        NSDate* date = [NSDate date]; //start date
        NSCalendar* calendar = [NSCalendar calendarWithIdentifier:NSCalendarIdentifierGregorian];
        NSDateComponents* components = [calendar components:(NSCalendarUnitMinute | NSCalendarUnitHour) fromDate:date];
        NSInteger minutes = [components minute];
        NSInteger hours = [components hour];

        NSInteger nearestGoodMinutes = [self _nearestGoodMinutesForMinutes:minutes];
        BOOL shouldIncHours = [self _shouldINcHoursForMinutes:minutes];
        if (shouldIncHours)
        {
            hours++;
        }
        NSDate* dateWithGoodHours = [calendar dateBySettingUnit:NSCalendarUnitHour value:hours ofDate:date options:kNilOptions];
        NSDate* goodDate = [calendar dateBySettingUnit:NSCalendarUnitMinute value:nearestGoodMinutes ofDate:dateWithGoodHours options:kNilOptions];

一些解释。 NSDate does not contain any date components. Date components depend on current callendar. Also values of the components depent on current time zone. If you create NSCalendar with identifier, you will get calendar in current time zone. The time zone should be same with time zone that you use for displaying 给用户的日期。

P.S.
您只能在开始日期这样做。

您可以用户Calendar Components设置分钟00然后计算间隔:

func getIntervals(start: String, end: String)->[Date]{
    let formatter = DateFormatter()
    formatter.dateFormat = "hh:mm a"

    var fromDate = formatter.date(from: start)!
    let calendar = Calendar(identifier: .gregorian)
    let component = calendar.dateComponents([.hour, .minute], from: fromDate)
    fromDate = calendar.date(bySettingHour: component.hour!, minute: 0, second: 0, of: fromDate)!

    let thirtyMin: TimeInterval = 1800
    let endDate = formatter.date(from: end)!
    var intervals = Int(endDate.timeIntervalSince(fromDate)/thirtyMin)
    intervals = intervals < 0 ? 0 : intervals

    var dates = [Date]()

    for x in 0...intervals{
        let date = fromDate.addingTimeInterval(TimeInterval(x)*thirtyMin)
        dates.append(date)
    }
    return dates 
}

let timeIntervals = getIntervals(start: "10:10 am", end: "1:40 pm")

如果用户输入的时间少于 30,则使用下面的函数,它将在接下来的 30 分钟内开始,例如 10:20,从 10:30 开始。如果用户给出的时间大于 30,那么非常时间将为 00,例如 10:45,从 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

}
func format(minute: Int) {
    let h = minute / 60
    let m = minute % 60
    timeLabel.text = "\(h.padZero()):\(m.padZero())"
}      


private extension Int {
    func padZero() -> String {
        return String(format: "%02d", self)
    }
}

参考这个posthttps://github.com/onmyway133/blog/issues/340