Swift 将小时从12小时转换为24小时,并保存为整数
我想将小时数的变量(一个整数)转换为24小时制(例如,如果是下午1:05:13,小时将保存为13,分钟将保存为5,秒将保存为13),以便我可以在以后的代码中使用它进行一些数学运算,从而在我正在使用的调度应用程序上消除一些差异。这是我的第一个应用程序,我在其他任何地方都找不到答案,所以谢谢你的帮助!这段代码的另一种工作方式是从一天开始就以秒为单位获取数量,如果有人知道如何做到这一点,我们将不胜感激! 这是我的函数,用于获取时间并将其保存为小时、秒和分钟的三个不同整数:Swift 将小时从12小时转换为24小时,并保存为整数,swift,swift3,nsdate,Swift,Swift3,Nsdate,我想将小时数的变量(一个整数)转换为24小时制(例如,如果是下午1:05:13,小时将保存为13,分钟将保存为5,秒将保存为13),以便我可以在以后的代码中使用它进行一些数学运算,从而在我正在使用的调度应用程序上消除一些差异。这是我的第一个应用程序,我在其他任何地方都找不到答案,所以谢谢你的帮助!这段代码的另一种工作方式是从一天开始就以秒为单位获取数量,如果有人知道如何做到这一点,我们将不胜感激! 这是我的函数,用于获取时间并将其保存为小时、秒和分钟的三个不同整数: @IBAction func
@IBAction func setTime() {
var date = NSDate()
//pickTimes()
var calendar = NSCalendar.current
calendar.timeZone = TimeZone(identifier: "UTC")!
var currentHour = calendar.component(.hour, from: date as Date) + 5
let currentMinutes = calendar.component(.minute, from: date as Date)
let currentSeconds = calendar.component(.second, from: date as Date)
timeText.text = ("\(currentHour):\(currentMinutes):\(currentSeconds)")
}
calendar.component(.hour,from:someDate)
已经为您提供了24小时内的一天时间,因此没有其他方法可以解决您的问题5
。您将时区设置为UTC,因此日期将被视为UTC时区。然后在结果上加5。这有点奇怪。如果您只想在用户的区域设置时区中显示当前小时,请不要更改日历的时区,也不要在小时中添加5
NSDate
或NSCalendar
。这是斯威夫特。使用日期
和日历
@IBAction func setTime() {
var date = Date()
//pickTimes()
var calendar = Calendar.current
var currentHour = calendar.component(.hour, from: date)
let currentMinutes = calendar.component(.minute, from: date)
let currentSeconds = calendar.component(.second, from: date)
timeText.text = ("\(currentHour):\(currentMinutes):\(currentSeconds)")
}
但是使用DateFormatter
并将timeStyle
设置为.medium
或.long
并将Date()格式化为字符串会更简单。这将提供一个正确本地化的时间字符串。可能的时间字符串重复