-2

I'm trying to modify the date format of a string in Swift.

I need to print my date to the french format :

17 mai 2015

I tried this :

var myDate = "2015-05-17 13:00:00"
var dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "d MMMM"
var readableDate = dateFormatter.dateFromString(myDate)
println("Readable date = \(readableDate!)")

I obtain a nil value when I run the program, and I don't understand why.

apgobert
  • 31
  • 6
  • 3
    Look at any of the ten thousand prior questions on this topic. (Or, horror of horrors, actually read the documentation.) – Hot Licks May 17 '15 at 18:31
  • If you have `myDate` as a string, then you really need two formatters, one to convert this `yyyy-MM-dd HH:mm:ss` string to a `NSDate` object, and another to convert that `NSDate` back into a string in your french format. And for this latter formatter, I might suggest you do not specify any `dateFormat` string and just specify a `dateStyle`, and let it represent the date in a format dictated by the end user's localization settings. – Rob May 17 '15 at 18:33
  • possible duplicate of [Swift - IOS - Dates and times in different format](http://stackoverflow.com/questions/28489227/swift-ios-dates-and-times-in-different-format) – BSMP May 17 '15 at 18:35
  • Also, it's not clear from your question as to whether the time in this original string is in the end-user's local time zone or GMT. So you might want to confirm that, too. – Rob May 17 '15 at 18:44

1 Answers1

0

.dateFromStringcreates an NSDate() from a String. The format of the string has to be set with .dateFormat

You set the format to "d MMMM" but your myDate variable does not conform to that format.

I believe you want to make a String in your "d MMMM" format out of a date. Take this code as a starting-point:

var dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "d MMMM"
var readableDate = dateFormatter.stringFromDate(NSDate())
println("Readable date = \(readableDate)")

Check out the Class Reference for NSDate for further assistance

gutenmorgenuhu
  • 2,312
  • 1
  • 19
  • 33