Pablo Picasso Pablo Picasso - 4 years ago 219
Swift Question

Get NSDate and convert it from the 24 hour format to 12 hour format in swift

I've seen this post for other languages but not for swift. I have a date saved in the format of

2015-08-31 21:36:00 +0000
and I'm able to extract the day, month, year and weekday with the code below to produce
Monday, August 31, 2015
. When I try to use:

let hourInt = components.hour
var hourString = String(hourInt)


It prints a four hour difference. In this case "17" for the "21". How do I
display it as
9:36 P.M.
?

let flags: NSCalendarUnit = NSCalendarUnit.CalendarUnitMinute | NSCalendarUnit.CalendarUnitHour | NSCalendarUnit.CalendarUnitDay | NSCalendarUnit.CalendarUnitWeekday | NSCalendarUnit.CalendarUnitMonth | NSCalendarUnit.CalendarUnitYear
let date = NSDate()
let dateFormatter: NSDateFormatter = NSDateFormatter()
let components = NSCalendar.currentCalendar().components(flags, fromDate: array.date)


let weekday = components.weekday
let weekdays = dateFormatter.weekdaySymbols
let weekdayString = weekdays[weekday-1] as! String

let month = components.month
let months = dateFormatter.monthSymbols
let monthString = months[month-1] as! String

let dayInt = components.day
var dayString = String(dayInt)

let year = components.year
let yearString = String(year)
println(weekdayString + ", " + monthString + " " + dayString + ", " + yearString)

Answer Source

Your date string suffix +0000 means it is UTC time if you want to display time at UTC you need to specify it when setting your date formatter.

let dateString = "2015-08-31 21:36:00 +0000"
let df = NSDateFormatter()
df.dateFormat = "yyyy-MM-dd HH:mm:ss Z"
if let date = df.dateFromString(dateString) {
    // now you have your date object
    // to display UTC time you have to specify timeZOne UTC
    df.timeZone = NSTimeZone(forSecondsFromGMT: 0)
    df.dateFormat = "EEEE, MMMM dd, yyyy h:mm:ss a"
    let stringFromDate = df.stringFromDate(date)
    println(stringFromDate)   // "Monday, August 31, 2015 9:36:00 PM"
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download