我正在尝试将 am/pm 格式时间转换为 24 小时格式时间
6:35 PM to 18:35
我在操场上尝试了这段代码,但似乎没有 如果我有时间独自工作
let dateAsString = "02/12/15, 6:35 PM"
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "HH"
let date = dateFormatter.dateFromString(dateAsString) //returns nil
有谁知道如何做到这一点?
只需使用 NSDateFormatter 和“h:mm a”格式将其转换为日期,然后使用“HH:mm”格式将其转换回字符串。查看此日期格式指南以熟悉此材料。
let dateAsString = "6:35 PM"
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "h:mm a"
dateFormatter.locale = Locale(identifier: "en_US_POSIX") // fixes nil if device time in 24 hour format
let date = dateFormatter.dateFromString(dateAsString)
dateFormatter.dateFormat = "HH:mm"
let date24 = dateFormatter.stringFromDate(date!)
斯威夫特3
时间格式24小时到12小时
let dateAsString = "13:15"
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "HH:mm"
let date = dateFormatter.date(from: dateAsString)
dateFormatter.dateFormat = "h:mm a"
let Date12 = dateFormatter.string(from: date!)
print("12 hour formatted Date:",Date12)
输出将为 12 小时格式日期:下午 1:15
时间格式12小时到24小时
let dateAsString = "1:15 PM"
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "h:mm a"
let date = dateFormatter.date(from: dateAsString)
dateFormatter.dateFormat = "HH:mm"
let Date24 = dateFormatter.string(from: date!)
print("24 hour formatted Date:",Date24)
输出将为 24 小时格式日期:13:15
斯威夫特 3 *
将 12 小时(即上午和下午)转换为 24 小时格式的代码,其中包括 -
时:分:秒:AM/PM 至时:分:秒
func timeConversion24(time12: String) -> String {
let dateAsString = time12
let df = DateFormatter()
df.dateFormat = "hh:mm:ssa"
let date = df.date(from: dateAsString)
df.dateFormat = "HH:mm:ss"
let time24 = df.string(from: date!)
print(time24)
return time24
}
输入
07:05:45PM
输出
19:05:45
同样
将 24 小时转换为 12 小时(即 AM 和 PM) 格式的代码,其中包括 -
小时:分钟:秒到小时:分钟:秒:AM/PM
func timeConversion12(time24: String) -> String {
let dateAsString = time24
let df = DateFormatter()
df.dateFormat = "HH:mm:ss"
let date = df.date(from: dateAsString)
df.dateFormat = "hh:mm:ssa"
let time12 = df.string(from: date!)
print(time12)
return time12
}
输入
19:05:45
输出
07:05:45PM
这是带有更多额外格式的答案。
** Xcode 12、Swift 5.3 **
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "HH:mm:ss"
var dateFromStr = dateFormatter.date(from: "12:16:45")!
dateFormatter.dateFormat = "hh:mm:ss a 'on' MMMM dd, yyyy"
//Output: 12:16:45 PM on January 01, 2000
dateFormatter.dateFormat = "E, d MMM yyyy HH:mm:ss Z"
//Output: Sat, 1 Jan 2000 12:16:45 +0600
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"
//Output: 2000-01-01T12:16:45+0600
dateFormatter.dateFormat = "EEEE, MMM d, yyyy"
//Output: Saturday, Jan 1, 2000
dateFormatter.dateFormat = "MM-dd-yyyy HH:mm"
//Output: 01-01-2000 12:16
dateFormatter.dateFormat = "MMM d, h:mm a"
//Output: Jan 1, 12:16 PM
dateFormatter.dateFormat = "HH:mm:ss.SSS"
//Output: 12:16:45.000
dateFormatter.dateFormat = "MMM d, yyyy"
//Output: Jan 1, 2000
dateFormatter.dateFormat = "MM/dd/yyyy"
//Output: 01/01/2000
dateFormatter.dateFormat = "hh:mm:ss a"
//Output: 12:16:45 PM
dateFormatter.dateFormat = "MMMM yyyy"
//Output: January 2000
dateFormatter.dateFormat = "dd.MM.yy"
//Output: 01.01.00
//Output: Customisable AP/PM symbols
dateFormatter.amSymbol = "am"
dateFormatter.pmSymbol = "Pm"
dateFormatter.dateFormat = "a"
//Output: Pm
// Usage
var timeFromDate = dateFormatter.string(from: dateFromStr)
print(timeFromDate)
下面是 swift 3 版本的解决方案 -
let dateAsString = "6:35:58 PM"
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "h:mm:ss a"
let date = dateFormatter.date(from: dateAsString)
dateFormatter.dateFormat = "HH:mm:ss"
let date24 = dateFormatter.string(from: date!)
print(date24)
Swift 版本 3.0.2,Xcode 版本 8.2.1 (8C1002)(12 小时格式):
func getTodayString() -> String{
let formatter = DateFormatter()
formatter.dateFormat = "h:mm:ss a "
formatter.amSymbol = "AM"
formatter.pmSymbol = "PM"
let currentDateStr = formatter.string(from: Date())
print(currentDateStr)
return currentDateStr
}
输出: 12:41:42 AM
欢迎评论。谢谢
使用此功能进行日期转换,当您的设备采用 24/12 小时格式时,它工作正常
参见https://developer.apple.com/library/archive/qa/qa1480/_index.html
func convertDateFormatter(fromFormat:String,toFormat:String,_ dateString: String) -> String{
let formatter = DateFormatter()
formatter.locale = Locale(identifier: "en_US_POSIX")
formatter.dateFormat = fromFormat
let date = formatter.date(from: dateString)
formatter.dateFormat = toFormat
return date != nil ? formatter.string(from: date!) : ""
}
不幸的是,苹果优先考虑设备日期格式,因此在某些情况下,根据您输入的内容,迅速将格式更改为 12 小时
要解决此问题,需要使用 setLocalizedDateFormatFromTemplate 而不是 dateFormat 并隐藏 AM 和 PM
let formatter = DateFormatter()
formatter.setLocalizedDateFormatFromTemplate("HH:mm:ss a")
formatter.amSymbol = ""
formatter.pmSymbol = ""
formatter.timeZone = TimeZone(secondsFromGMT: 0)
var prettyDate = formatter.string(from: Date())
您可以查看一篇非常有用的帖子,其中详细介绍了更多信息 https://prograils.com/posts/the-curious-case-of-the-24-hour-time-format-in-swift
这是其他方式的代码
对于 Swift 3
func amAppend(str:String) -> String{
var temp = str
var strArr = str.characters.split{$0 == ":"}.map(String.init)
var hour = Int(strArr[0])!
var min = Int(strArr[1])!
if(hour > 12){
temp = temp + "PM"
}
else{
temp = temp + "AM"
}
return temp
}
let calendar = Calendar.current
let hours = calendar.component(.hour, from: Date())
let minutes = calendar.component(.minute, from: Date())
let seconds = calendar.component(.second, from: Date())
在我的例子中,我在这里使用一个函数,通过该函数我用正常时间格式更新标签,然后我存储所选时间的 24 小时格式以执行其他一些任务..
这是我的代码...
func timeUpdate(sender: NSDate)
{
let timeSave = NSDateFormatter() //Creating first object to update time label as 12hr format with AM/PM
timeSave.timeStyle = NSDateFormatterStyle.ShortStyle //Setting the style for the time selection.
self.TimeShowOutlet.text = timeSave.stringFromDate(sender) // Getting the string from the selected time and updating the label as 1:40 PM
let timeCheck = NSDateFormatter() //Creating another object to store time in 24hr format.
timeCheck.dateFormat = "HH:mm:ss" //Setting the format for the time save.
let time = timeCheck.stringFromDate(sender) //Getting the time string as 13:40:00
self.timeSelectedForCheckAvailability = time //At last saving the 24hr format time for further task.
}
编写此函数后,您可以在从日期/时间选择器中选择时间时调用此函数。
谢谢, 希望这有帮助。
这与我们朋友的答案类似:https://stackoverflow.com/a/43801717/2796837但是利用我们所有互联网朋友的想法,我想出了以下更完整的单一解决方案:
let amPmFormat = "h:mm a"
let twentyFourHFormat = "HH:mm"
func hourMinuteParser(date: Date) -> KotlinInt{
let formatter = DateFormatter()
if DateFormatter.dateFormat(fromTemplate: "j",options:0, locale: Locale.current)!.contains("a") {
formatter.dateFormat = amPmFormat
}else{
formatter.dateFormat = twentyFourHFormat
}
let stringTime = formatter.string(from: date)
let time = formatter.date(from: stringTime)
formatter.dateFormat = twentyFourHFormat
let time24 = formatter.string(from: time!)
let timeWithoutSpecialCharacters = time24.replacingOccurrences(of: ":", with: "")
let int2 = Int32(timeWithoutSpecialCharacters) ?? 0
return KotlinInt(int: int2)
}
这将解析您的时间,甚至与它的格式无关,并将其输出为 HH:mm,您可以将第三个格式更改为您想要的任何格式。
为了方便起见,我添加了以下字符串扩展:
import Foundation
extension String {
// Converts 24-hour format to 12-hour format
// Input: 22:15
// Output: 10:15 PM
var time12String: String {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "HH:mm"
guard let date = dateFormatter.date(from: self) else {
return "Invalid Time String"
}
dateFormatter.dateFormat = "hh:mm a"
return dateFormatter.string(from: date)
}
// Converts 12-hour format to 24-hour format
// Input: 10:15 PM
// Output: 22:15
var time24String: String {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "hh:mm a"
guard let date = dateFormatter.date(from: self) else {
return "Invalid Time String"
}
dateFormatter.dateFormat = "HH:mm"
return dateFormatter.string(from: date)
}
}
用途:
let timeIn12Hour = "22:15".time12String
print(timeIn12Hour)
// Output: 10:15 PM
let timeIn24Hour = "10:15 PM".time24String
print(timeIn24Hour)
// Output: 22:15
从你的问题假设你不关心这里的日期。如果您需要日期,则需要正确更新格式