rome 웃
rome 웃

Reputation: 1901

Format String to HH:mm in Swift

My code:

let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
let date = dateFormatter.dateFromString("2015-09-01 00-32-40")

Result: 2015-08-31 17:32:40

But I want get result like this: 17:32. How do I resolve it?

Upvotes: 5

Views: 14654

Answers (1)

Lyndsey Scott
Lyndsey Scott

Reputation: 37290

If you're trying to get an NSDate and not a string representation, printing the NSDate will always show the full date time. To just show the hours and minutes, you'll have to create a string representation using an "HH:mm" date format, ex:

// Your original code
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
let date = dateFormatter.dateFromString("2015-09-01 00-32-40")

// To convert the date into an HH:mm format
dateFormatter.dateFormat = "HH:mm"
let dateString = dateFormatter.stringFromDate(date!)
println(dateString)

Not sure why you're looking to get a result of "17:32", but this will produce "00:32" as a result from the original "00-32" portion of the string.

Upvotes: 23

Related Questions