想要获得Time数组

时间:2017-07-01 06:57:44

标签: ios swift time

我正在尝试获取时间数据,其中时间将从当前时间+ 1小时开始,之后到下午5点将显示30-30分钟时间之间的差异。

func getTimeArray(){
    let date = Date()
    var dateComponents = DateComponents()
    let timeFormatter = DateFormatter()

    let calendar = Calendar.current
    var components = calendar.dateComponents([.hour , .minute], from: date)

    dateComponents.hour = components.hour
    dateComponents.minute = components.minute
    timeFormatter.dateFormat = "h:mm a"

    guard let startTime = calendar.date(from: dateComponents) else {
        return }
    for i in 0 ... 10 {
        guard let  newDate = calendar.date(byAdding: .minute , value: i + 30, to: startTime) else {return}
        timeArray.append(timeFormatter.string(from: newDate).localizedUppercase)
        print(timeArray)
    }

    print(timeArray)

}

结果是: - [&#34; 12:53 PM&#34;,&#34; 12:54 PM&#34;,&#34; 12:55 PM&#34;,&#34; 12 :下午56点&#34;,&#34; 12:57 PM&#34;,&#34; 12:58 PM&#34;,&#34; 12:59 PM&#34;,&#34; 1:00 PM&#34;,&#34; 1:01 PM&#34;,&#34; 1:02 PM&#34;,&#34; 1:03 PM&#34;] 我需要: - [&#34; 12:30&#34;,&#34; 1:00&#34;,&#34; 1:30&#34;,&#34; 2:00&#34;] < / p>

2 个答案:

答案 0 :(得分:1)

更符合您需求的更有条理的方式:

func getTimeArray(){
        var timeArray = [String]()
        let timeFormatter = DateFormatter()
        timeFormatter.dateFormat = "h:mm"

        for i in 0 ... 10 {
            guard let dt:Date = Calendar.current.date(byAdding: .minute, value: 30*i, to: Date()) else {return}
            timeArray.append(timeFormatter.string(from: dt).localizedUppercase)

        }
        print(timeArray)
    }

答案 1 :(得分:0)

关于如何设置日期格式的全部内容。您可以引用不同的时间格式NSDateFormatter.com

您的修复:

timeFormatter.dateFormat = "h:mm a"更改为timeFormatter.dateFormat = "h:mm"