How to set Date and time from UIDatePicker to UITextField in 12 hours format

2.2k views Asked by At

If system date is in 24 hours format. I want to set selected date and time in 12 hours format with AM/PM to textfield as input view. I am trying to convert selected date and time but its giving me 24 hours format. Can anyone please help me. Here is my code for conversion:

    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "yyyy-MM-dd HH:mm"
    let dateAsString = dateFormatter.string(from: datePickerView.date)

    dateFormatter.dateFormat = "yyyy-MM-dd h:mm a"
    let date = dateFormatter.date(from: dateAsString)
    let DateIn12 = dateFormatter.string(from: date!)
    print("12 hour formatted Date:", DateIn12)
5

There are 5 answers

1
Sudhir kumar On

Replace your code to convert 24 hour date into 12 hour format with following code

   let formatter = DateFormatter()
    //Formatter "yyyy-MM-dd HH:mm a" for 24 hours time
    // "yyyy-MM-dd hh:mm a" for 12 hours time
    // So you need to write only
    formatter.dateFormat = "yyyy-MM-dd hh:mm a"
    let twelveHourDate = formatter.string(from: datePickerView.date)
    print("12 hour format date is \(twelveHourDate)")
0
AudioBubble On

dateFormat = "yyyy-MM-dd h:mm a"

To get time in 24 hours format uppercased "H" is used in the formatter while lowercased "h" gives you the time in 12 hour format.

So you can create the dateformatter everytime on your own keeping this in mind.

Thanks.

0
Pranav Kasetti On

You seem to be doing unnecessary work here.

Given you already have a date, this should work:

let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd h:mm a"
let date12 = dateFormatter.string(from: datePickerView.date)
print("12 hour formatted Date:", date12)
0
iCyberPaul On

You can get the date in any format you want from the date picker's date value. Here are a couple of options that might help.

let datePickerView = UIDatePicker()
datePickerView.date = Date()
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd h:mm a"
var dateAsString = dateFormatter.string(from: datePickerView.date)
print(dateAsString)
dateFormatter.dateFormat = "MMM-yy-dd HH:mm"
dateAsString = dateFormatter.string(from: datePickerView.date)
print(dateAsString)

This gives

2017-09-18 1:18 PM
Sep-17-18 13:18

You should not need the second half of your code.

2
Hitesh On

You need pass datepickerview.date in dateformatter. try this

let dateFormatter = DateFormatter()
print("Date:=\(datePickerView.date)")
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss a"
let DateIn12 = dateFormatter.string(from: datePickerView.date)  
print("12 hour formatted Date:", DateIn12)