如何在swift 2.3中制作30分钟的时间间隔

时间:2016-11-10 11:17:29

标签: ios swift time nsdate

startTime = 10:00 AM endTime = 01:00 PM

现在我想以30分钟的间隔分割时间,如

10:00 AM 10:30 AM 11:00 AM 11:30 AM ..........直到01:00 PM。

我试过

   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 ..等等 如何制作30分钟的间隔,如10:00,10:30 ......等。

提前致谢

4 个答案:

答案 0 :(得分:2)

如果用户进入任何时间少于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

}

答案 1 :(得分:0)

您可以使用NSDateComponents课程。这个类允许获得一些日期单位。您可以从日期获取分钟和小时值,并将分钟数转到最接近的“好”值(有时您也应该更改小时数)。
之后,您可以使用新的小时和分钟值来获取新日期。 不要忘记时区。

        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不包含任何日期组件。日期组件取决于当前callendar。此外,组件的值取决于当前时区。如果您使用标识符创建NSCalendar,您将获得当前time zone中的日历。时区应与您用于日期displaying的时区相同。

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

答案 2 :(得分:0)

您可以使用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")

答案 3 :(得分:0)

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)
    }
}

已引用此帖子https://github.com/onmyway133/blog/issues/340