Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 453
rome 웃 Avatar asked Nov 29 '22 23:11

rome 웃


1 Answers

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.

like image 136
Lyndsey Scott Avatar answered Dec 04 '22 13:12

Lyndsey Scott