let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss";
dateFormatter.timeZone = TimeZone.current;
dateFormatter.dateStyle = .none;
dateFormatter.timeStyle = .none;
let date = dateFormatter.date(from: "2023-08-03 00:00:00")
this date is nil, why ?
let dateFormatter = DateFormatter()
dateFormatter.dateStyle = .none
dateFormatter.timeStyle = .none
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
dateFormatter.timeZone = TimeZone.current
let date = dateFormatter.date(from: "2023-08-03 00:00:00")
this date is correct
What causes this?I need help`
3
Answers
Either remove dateStyle and timeStyle from code or if you want to use them then declare your dateFormat after it
Writing these lines means you are setting the style of the date while requesting the format later causing it to have a proper value to save whereas writing these lines after the format declaration somehow causes a loss in its value
You should only set either
dateFormat
or the twodateStyle
andtimeStyle
. Don’t ever set all three.If you first set
dateFormat
and then you setdateStyle
andtimeStyle
, the set styles override any set format.In the first example, since you set both styles to
.none
, the format, set first, is lost and no style is set so the formatter can’t parse any strings.Your second example works because you set the format last so it overrides the styles you set. This allows the date formatter to parse the string.
The use of styles it typically only used when you want to convert a Date to a String for display to the user.
The use of a specific format is typically used when you need to parse a fixed format string and convert it into a Date. A date format can also be used when you have a Date that needs to be formatted to a fixed format for sending the string to a server. You rarely want to use a date format to display the Date to a user because then it won’t always be in the user’s preferred style for their locale.