11

To convert date and time, I have used this:

 let formatter = NSDateFormatter()
 formatter.calendar = NSCalendar(calendarIdentifier: NSCalendarIdentifierISO8601)
 formatter.locale = NSLocale(localeIdentifier: "en_US_POSIX")
 formatter.timeZone = NSTimeZone(forSecondsFromGMT: 0)
 formatter.dateFormat = "M/dd/yyyy, h:mm"
 formatter.AMSymbol = "AM"
 formatter.PMSymbol = "PM"
 let dateString = formatter.stringFromDate(model.courseDate)
 print(dateString)

If the course date is "courseDate = "2017-01-09 01:00:00 +0000";" but I am getting like this in print: 1/09/2017, 1:00 with no any AM or PM.

How can I achieve this?

Thanks.

Ahmad F
  • 30,560
  • 17
  • 97
  • 143
Sam
  • 449
  • 2
  • 9
  • 18

3 Answers3

12

according to the date formatter specs

You can retrieve a date in 24h format instead of requesting AM/PM by using HH instead of hh

so the date "21/11/2016 01:30" (pm) would be "21/11/2016 13:30".

if you do need to print the format, though, you can print it using:

a

More date fomatting details here

CptEric
  • 897
  • 9
  • 23
8

As per Apple general date formatter you should use "M/dd/yyyy, hh:mm a" in your date format.

like : formatter.dateFormat = "M/dd/yyyy, hh:mm a"

Hope this will help you!

CodeChanger
  • 7,953
  • 5
  • 49
  • 80
Shivani Gor
  • 329
  • 1
  • 8
1

use following code may help full for you

//Call function

let dateTime = self.convertDateFormaterAamer(sendTimeStep, inputDateFormate: "dd-MM-yyyy HH:mm:ss", outputDateFormate: "dd-MMM-yyyy hh:mm a")

//Date function

func convertDateFormater(date: String,inputDateFormate: String , outputDateFormate: String) -> String
{
    let dateFormatter = NSDateFormatter()
    //dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
    //dateFormatter.timeZone = NSTimeZone(name: "UTC")
    dateFormatter.dateFormat = inputDateFormate


    let date = dateFormatter.dateFromString(date)

    //dateFormatter.dateFormat = "yyyy MMM EEEE HH:mm"
    //dateFormatter.timeZone = NSTimeZone(name: "UTC")
    dateFormatter.dateFormat = outputDateFormate
    var timeStamp = ""
    if (date != nil)
    {
        timeStamp = dateFormatter.stringFromDate(date!)
    }
    return timeStamp
}
Mitesh jadav
  • 910
  • 1
  • 9
  • 26