gpt4 book ai didi

当下午时,Swift 时间返回为上午

转载 作者:行者123 更新时间:2023-11-30 10:10:18 24 4
gpt4 key购买 nike

该函数获取当前时间并在数组中查找下一个时间。当当前时间在中午之前并且下一个时间在中午之后时,它会在应该是下午的情况下将下一次时间返回为上午。我怎样才能改变这个?我需要使用 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)


}

最佳答案

尝试在 dateFormat 中使用大写 H:

dateMakerFormatter.dateFormat = "H:mm"

关于当下午时,Swift 时间返回为上午,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33332765/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com