xcode swift am / pm时间为24小时格式

时间:2015-03-28 20:02:36

标签: swift time

我正在尝试将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

有谁知道如何做到这一点?

谢谢。

11 个答案:

答案 0 :(得分:116)

只需使用NSDateFormatter和“h:mm a”格式将其转换为日期,然后使用“HH:mm”格式将其转换回字符串。请查看此date formatting guide以熟悉此材料。

enter image description here

let dateAsString = "6:35 PM"
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "h:mm a"
let date = dateFormatter.dateFromString(dateAsString)

dateFormatter.dateFormat = "HH:mm"
let date24 = dateFormatter.stringFromDate(date!)

答案 1 :(得分:35)

Swift 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

答案 2 :(得分:5)

以下是解决方案的快速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)

答案 3 :(得分:2)

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

随意发表评论。感谢

答案 4 :(得分:1)

不幸的是,苹果将设备日期格式设置为优先级,因此在某些情况下,与您输入的内容不同,请迅速将格式更改为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

答案 5 :(得分:1)

使用此功能进行日期转换,当您的设备在24/12小时的时间内进行格式化时,它可以正常工作

func convertDateFormater(fromFormate:String,toFormate:String,_ dateString: String) -> String{
    let formatter = DateFormatter()
    formatter.locale = NSLocale(localeIdentifier: "en_US_POSIX") as Locale
    formatter.dateFormat = fromFormate
    let date = formatter.date(from: dateString)
    formatter.dateFormat = toFormate
    return  date != nil ? formatter.string(from: date!) : ""
}

答案 6 :(得分:1)

这是更多格式的答案。

** 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)

答案 7 :(得分:0)

在我的情况下,我正在使用一个函数,我正在使用正常的时间格式更新标签,之后我将存储所选时间的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.
}

编写此功能后,您可以在选择日期/时间选择器的时间时调用此功能。

谢谢, 希望这有帮助。

答案 8 :(得分:0)

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())

答案 9 :(得分:0)

快捷键3 *

12小时(即上午和下午)转换为24小时格式的代码,其中包括-

  

小时:分钟:秒:AM / PM到小时:分钟:秒

<select name="tag_type" id="id_tag_type">
  <option value="P">Positive</option>
  <option value="N" selected>Negative</option>
</select>

输入

  

07:05:45 PM

输出

  

19:05:45

类似地

24小时转换为12小时(即上午和下午)格式的代码,其中包括-

  

小时:分钟:秒至小时:分钟:秒: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
}

输入

  

19:05:45

输出

  

07:05:45 PM

答案 10 :(得分:0)

这类似于我们朋友的回答: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,您可以将第三种格式更改为您想要的任何格式。