I have a date in a string with this format "2017-03-14" (yyyy-MM-dd) and i am trying to convert it into a string with this format "Tuesday, March 14, 2017".
This is my code:
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
let date = dateFormatter.date(from: "2017-03-14")
Now if i print the value of "date", i get this:
2017-03-13 22:00:00 +0000
This is just the day before. Why is that ?
EDIT:
I need to compare date before formatting it.
var newDateString : String = ""
let date2 = Date()
let comp = date2.compare(date!)
if comp.rawValue == 0 {
newDateString = "TONIGHT"
} else {
dateFormatter.dateFormat = "EEEE, MMMM d, yyyy"
newDateString = dateFormatter.string(from: date!)
}
Thanks
Your confusion is based on a misunderstanding of what Time and Date are. Evidently, you are currently located in a time zone that is 2 hours ahead of UTC (Coordinated Universal Time), previously known as Greenwich Mean Time (GMT).
When you ask the OS for a Date object converted from "2017-03-14" you get a date/time reference of Midnight the morning of 2017-03-14 in your time zone which is, correctly, 10:00 pm (22:00) then night before in UTC.
When you ask the OS for a Date object for now with
Date()
you get a date/time reference of now in your time zone, which will be two hours earlier in UTC.To accurately evaluate your date string to say "is now earlier than 'tonight of 2017-03-14'" you will probably want to convert from "2017-03-14 23:59" (or 11:59 pm, or perhaps prior to the start of tonight's event of 8:00 pm, etc).
This will do your original comparison, but would work better as a function (although I'm not sure how you want to use it)...
The desired Format should be:
All you have to do is to add after your code the following code snippet:
Remark:
I'd like to suggest to do optional binding for declaring the
date
, as follows:It is calculated time based on UTC so you are getting day before.You can get proper format using below code:
For comparison you also need to convert
Date()
to proper format.Both date must be in same format.Now you can compare two strings