快速时间在下午返回时

时间:2015-10-25 17:33:47

标签: swift nsdate

此函数获取当前时间并在数组中查找下一次。当前时间是在中午之前,下一次是在中午之后,它会在下一次返回到应该是下午的时间。 我怎么能改变这个?我需要使用12小时而不是24小时制吗?

import UIKit
import Foundation

let date = NSDate()
let calendar = NSCalendar.currentCalendar()
let components = calendar.components([.Hour, .Minute], fromDate: date)
let hour = components.hour
let minutes = components.minute
let currentTime = "\(hour)" + ":" + "\(minutes)"  //output 10:47


let timesArray = ["5:45", "6:35", "7:00", "7:30", "7:50", "8:20", "8:40", "9:15", "10:10",
    "12:40", "14:15", "14:50", "15:40", "16:10", "17:10", "17:40", "18:40", "19:25", "20:50"]

// create a method to convert your time to minutes
func stringToMinutes(input:String) -> Int {
    let components = input.componentsSeparatedByString(":")
    let hour = Int((components.first ?? "0")) ?? 0
    let minute = Int((components.last ?? "0")) ?? 0
    return hour*60 + minute
}

//create an array with the minutes from the original array
let timesMinutesArray:[Int] = timesArray.map { stringToMinutes($0) }

let dayMinute = stringToMinutes(currentTime)
// filter out the times that has already passed
let filteredTimesArray = timesMinutesArray.filter{$0 > dayMinute }

// get the first time in your array
if let firstTime = filteredTimesArray.first {
    // find its position and extract it from the original array
    let nextDeparture = timesArray[timesMinutesArray.indexOf(firstTime)!]   // output  "12:40"


    let userCalendar = NSCalendar.currentCalendar()


    let dateMakerFormatter = NSDateFormatter()
    dateMakerFormatter.calendar = userCalendar
    dateMakerFormatter.dateFormat = "yyyy/MM/dd"



    // How many hours and minutes between current time and next departure?

    dateMakerFormatter.dateFormat = "h:mm"
    let startTime = dateMakerFormatter.dateFromString(currentTime)!
    let endTime = dateMakerFormatter.dateFromString(nextDeparture)! //this comes back as 12:40 am not pm
    let hourMinuteComponents: NSCalendarUnit = [.Hour, .Minute]
    let timeDifference = userCalendar.components(
        hourMinuteComponents,
        fromDate: startTime,
        toDate: endTime,
        options: [])

    let difference = (timeDifference.hour*60) + (timeDifference.minute)


}

1 个答案:

答案 0 :(得分:1)

dateFormat中尝试大写字母H:

dateMakerFormatter.dateFormat = "H:mm"