Reputation: 182
Using JSON, I'm pulling a date from my database which is formatted as Y-m-d in php. E.g. 2015-05-27.
I have stored the date in swift and can see it formatted when I print the string in the same way. I have followed the other answers and tutorials to try and convert the date into dd-MM-yyyy, but each time I am returned 'nil'.
If I try to convert the date to yyyy-MM-dd I will get '2015-05-26 23:00:00 +0000'
My code:
var survey_date = prefs.valueForKey("SURVEY_DATE") as! String
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "dd-MM-yyyy"
var date = dateFormatter.dateFromString(survey_date) as NSDate!
println(date)
self.survey_date.text = "Your survey is scheduled for \(date)"
Upvotes: 2
Views: 2516
Reputation: 8473
You've set your date formatter's dateFormat
property to dd-MM-yyyy
, but the string in survey_date
formatted as yyyy-MM-dd
. As a result, the value for date in this line...
var date = dateFormatter.dateFromString(survey_date) as NSDate!
is nil
. That's an easy fix -- change dateFormat
to yyyy-MM-dd
.
Printing out an NSDate
in yyyy-MM-dd
format is also an easy fix. Just as you used NSDateFormatter
's dateFromString()
method to convert a string whose format is specified by its dateFormat
property into an NSDate
, use NSDateFormatter
's stringFromDate()
method to convert an NSDate
into a string with dateFormat
's format.
Here's your code, with these two fixes applied:
var survey_date = prefs.valueForKey("SURVEY_DATE") as! String
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
var date = dateFormatter.dateFromString(survey_date) as NSDate!
let outputDate = dateFormatter.stringFromDate(date)
println(outputDate)
self.survey_date.text = "Your survey is scheduled for \(outputDate)"
Upvotes: 1
Reputation: 131471
Your code using a date formatter is correct, and is actually working correctly.
Date formatters default to the user's current time zone, so the date you enter as "2015-05-27" will be assumed to be midnight (I think) on that day in your local time zone.
Println displays the date in UTC, so you are seeing the output in UTC. Apparently you are in UTC+1, so the date shows up as 11:00 PM the day before.
You can use another date formatter to output your date as a string in your local time zone in whatever format you want.
Upvotes: 1
Reputation: 39409
Reading other answers on this site, it appears that Swift doesn’t have a native Date object but you can instead use the Cocoa NSDate
object:
var date = Date.parse("2014-05-20")
The second parameter is format, which defaults to yyyy-MM-dd
(which is what MySQL dates are).
I imagine once you have a NSDate
object you’ll then be able to print it in a format of your choosing.
Upvotes: 0