In the images below you can see the code I wrote and the values of all the variables:
class fun getCurrentShortDate() -> String {
var todaysDate = NSD
You can create a extension for easily transform a String
into a NSDate
.
extension NSDate {
func dateFromString(date: String, format: String) -> NSDate {
let formatter = NSDateFormatter()
let locale = NSLocale(localeIdentifier: "en_US_POSIX")
formatter.locale = locale
formatter.dateFormat = format
return formatter.dateFromString(date)!
}
}
Than in your function you can NSDate().dateFromString("2015-02-04 23:29:28", format: "yyyy-MM-dd HH:mm:ss")
and this should works. Input date don't need to be on the same format of output date.
func getCurrentShortDate() -> String {
var todaysDate = NSDate().dateFromString("2015-02-04 23:29:28", format: "yyyy-MM-dd HH:mm:ss")
var dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "dd-MM-yyyy"
var DateInFormat = dateFormatter.stringFromDate(todaysDate)
return DateInFormat
}
println(getCurrentShortDate())
The output is 04-02-2015
.