am/pm time to 24 hour format
Asked Answered
H

13

98

I am trying to convert an am/pm format time to a 24 hour format time

6:35 PM to 18:35

I tried this piece of code on playground but it doesn't seem to work if I put the time alone

let dateAsString = "02/12/15, 6:35 PM"
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "HH"
let date = dateFormatter.dateFromString(dateAsString) //returns nil

Does anyone know how to accomplish this?

Heaviside answered 28/3, 2015 at 20:2 Comment(1)
import UIKit let date = Date() print(" Date:",date) let dateFormatter = DateFormatter() dateFormatter.dateFormat = "h:mm a" let Date12Hr = dateFormatter.string(from: date) print("12 hour formatted Date:",Date12) this work fine in playground or Simulator ..while running in device its not converted ???Fourhanded
S
191

Just convert it to a date using NSDateFormatter and the "h:mm a" format and convert it back to a string using the "HH:mm" format. Check out this date formatting guide to familiarize yourself with this material.

enter image description here

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!)
Slightly answered 28/3, 2015 at 20:17 Comment(6)
This code gives nil if device time in 24 hour format. Any advice?Gurgle
try this Add following line after dateFormatter declaration. dateFormatter.locale = NSLocale(localeIdentifier: "en_US_POSIX") as Locale! This resolve my issue.Sollows
@Gurgle @ Nipul Daki I gave locale identifier and problem is solved! formatter.locale = Locale(identifier: "en_US_POSIX")Eruct
but why does it even return nil when the device is in 24 hours format? Why does it even effect the date (of nil) when specifying the dateFormat itself? @BurcuKutluayAdenectomy
Thanks for mentioning the reason of you using an explicit localeJahn
@BurcuKutluay Thank you. dateFormatter.locale = Locale(identifier: "en_US_POSIX") this line saved my time.Turley
W
70

Swift 3

Time format 24 hours to 12 hours

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)

output will be 12 hour formatted Date: 1:15 PM

Time format 12 hours to 24 hours

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)

output will be 24 hour formatted Date: 13:15

Waterside answered 5/5, 2017 at 9:45 Comment(4)
When changing from 24-hour to 12-hour format, I need to add dateFormatter.locale = Locale(identifier: "en_US_POSIX") to force it to ignore device locale.Weather
it is just a conversion of the date!Waterside
You can try setting device to 24-hour format. The code above doesn't work in my case.Weather
This is the only thing that worked for my out of all the crap I found out there to transform AM/PM time into 24h time. ThanksAccessible
M
19

Swift 3 *

Code to convert 12 hours (i.e. AM and PM) to 24 hours format which includes-

Hours:Minutes:Seconds:AM/PM to Hours:Minutes:Seconds

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
}

Input

07:05:45PM

Output

19:05:45

Similarly

Code to convert 24 hours to 12 hours (i.e. AM and PM) format which includes-

Hours:Minutes:Seconds to Hours:Minutes:Seconds: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
}

Input

19:05:45

Output

07:05:45PM

Montero answered 1/6, 2019 at 13:26 Comment(0)
D
8

Here is the answer with more extra format.

** 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)
Disyllable answered 27/10, 2020 at 2:57 Comment(0)
P
5

Below is the swift 3 version of the solution -

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)
Photocell answered 17/7, 2017 at 20:29 Comment(0)
R
4

Swift version 3.0.2 , Xcode Version 8.2.1 (8C1002) (12 hr format ):

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 
}

OUTPUT : 12:41:42 AM

Feel free to comment. Thanks

Ropable answered 3/9, 2017 at 19:20 Comment(5)
This question is about going from 12 hour time to 24 hour time, this answer deals with going in the other direction.Wrapping
Not correct answer!! You are confused because you are testing with 12:41:42. Try 1pm or greater.Szymanowski
hi if a user input 6:11AM, how can i convert to 2019-03-09 13:38:32 +0000 in this formatPress
so you have to use current date with time ( input provided by user)Ropable
this work fine in playground and Simulator ..while running in device its not convertedFourhanded
M
3

Use this function for date conversion, its working fine when your device in 24/12 hr format

See 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!) : ""
}
Metchnikoff answered 2/3, 2020 at 14:48 Comment(0)
C
2

Unfortunately apple priority the device date format, so in some cases against what you put, swift change your format to 12hrs

To fix this is necessary to use setLocalizedDateFormatFromTemplate instead of dateFormat an hide the AM and 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())

You can check a very useful post with more information detailed in https://prograils.com/posts/the-curious-case-of-the-24-hour-time-format-in-swift

Cordage answered 26/2, 2020 at 3:33 Comment(0)
P
1

Here is code for other way around

For 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
}
Pippy answered 22/2, 2017 at 9:39 Comment(1)
Shouldn't it be (hour >= 12) - since 12.00 noon is 12 p.m. and 00.00 midnight is 12 a.m.Lulualaba
G
1
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())
Gramnegative answered 21/5, 2019 at 15:58 Comment(1)
This isn't military time.Hauger
T
0

I am using a function here in my case by which I am updating a label with the normal time format and after that I am storing the selected time's 24hr format to do some another tasks..

Here is my code...

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.
}

After writing this function you can call this where you are choosing the time from date/time picker.

Thanks, Hope this helped.

Tortile answered 28/12, 2015 at 9:12 Comment(0)
A
0

this is similar to our friends answer: https://mcmap.net/q/216485/-am-pm-time-to-24-hour-format but using all our internet friends ideas I came up with the following more complete singular solution:

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

This will parse your time even independent of the format it comes and outputs it into HH:mm, you could change the third format change into whatever you would want.

Accessible answered 25/4, 2021 at 1:15 Comment(0)
G
0

I added the following String extension for ease:

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"
        dateFormatter.locale = Locale(identifier: "en_US_POSIX")
        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"
        dateFormatter.locale = Locale(identifier: "en_US_POSIX")
        guard let date = dateFormatter.date(from: self) else {
            return "Invalid Time String"
        }
        dateFormatter.dateFormat = "HH:mm"
        return dateFormatter.string(from: date)
    }
}

Usage:

let timeIn12Hour = "22:15".time12String
print(timeIn12Hour)
// Output: 10:15 PM

let timeIn24Hour = "10:15 PM".time24String
print(timeIn24Hour)
// Output: 22:15

Assuming from your question that you don't care about date here. If you need date then format needs to be updated properly

Grannias answered 18/2 at 9:3 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.