The DateFormatter help in the conversion between dates and textual representations.
For example :-
If you are working on the project and you are dealing with date or time to show in your app screen, the date or time format you receive is different from the format you want to display. Let say you got the date in "2017-11-15" and you need to display on screen as "15 November, 2017" so DateFormatter help us for conversion in the format as we want to display.
Now let's see some more example for date and time conversion.
Let assume we have the date in "2017-11-15" format and now we will see how we change the date in "15 November, 2017".
let originalDate = "2017-11-15" var newDate = "" let dateformatter = DateFormatter() dateformatter.dateFormat = "yyyy-MM-dd" let convertStringToDate = dateformatter.date(from: originalDate) dateformatter.dateFormat = "dd MMMM, yyyy" newDate = dateformatter.string(from: convertStringToDate!)
Now, let's customise the date in "15 Nov, 2017". For this you need to change only one line from the above code
dateformatter.dateFormat = "dd MMM, yyyy"
If you don't want to customise your date style, you can use default dateStyle property provided by apple and display the date like.
dateformatter.dateStyle = .long
For short date style you can use
dateformatter.dateStyle = .short
For full date with day of the week you can use
dateformatter.dateStyle = .full
For medium date style you can use
dateformatter.dateStyle = .medium
Subscribe to Engineering At Kiprosh
Get the latest posts delivered right to your inbox