Swift Date formatting and String to Date Conversion

The DateFormatter class is a subclass of the Formatter abstract class that can be used to convert a Date object into a human-readable string. It can also be used to convert a String representation of a date into a Date object. The DateFormatter type has five predefined styles that we can use.

  • Style = .none 
    • No format 
  • Style = .short 
    • 3/24/19, 11:01 PM
  • Style = .medium 
    • Mar 24, 2019 at 11:01:48 PM
  • Style = .long 
    • March 24, 2019 at 11:01:48 PM EDT
  • Style = .full 
    • Sunday, March 24, 2019 at 11:01:48 PM Eastern Daylight Time

import UIKit

let currentDate = Date()
var myFormat = DateFormatter()

//Just Date = 3/24/19
myFormat.dateStyle = .short
myFormat.timeStyle = .none
print(myFormat.string(from: currentDate))

//Just Time = 10:46 PM
myFormat.dateStyle = .none
myFormat.timeStyle = .short
print(myFormat.string(from: currentDate))
//Result = 3/24/19

//Short Date and Time = 10:46 PM
myFormat.dateStyle = .short
myFormat.timeStyle = .short
print(myFormat.string(from: currentDate))

//Medium Date and Time = Mar 24, 2019 at 10:49:04 PM
myFormat.dateStyle = .medium
myFormat.timeStyle = .medium
print(myFormat.string(from: currentDate))

//Long Date and Time = March 24, 2019 at 10:49:04 PM EDT
myFormat.dateStyle = .long
myFormat.timeStyle = .long
print(myFormat.string(from: currentDate))


//Full Date and Time = Sunday, March 24, 2019 at 10:49:04 PM Eastern Daylight Time
myFormat.dateStyle = .full
myFormat.timeStyle = .full
print(myFormat.string(from: currentDate))

Convert Date using a Custom String Format

For custom formatting we have to use standard characters based on how we want the date to display. The DateFormatter instance will replace these characters with the appropriate values. The following table shows some of the formatting values that we can use...
Standard String Description Output
yy Two-digit year 19, 20, 02
yyyy Four-digit year 2019, 2020, 2002
MM Two-digit month 04, 05, 06
MMM Three-letter month Apr, May, Jun
MMMM Full month name April, May, June
dd Two-digit day 10, 11, 20
EEE Three-letter day Mon, Sat, Sun
EEEE Full day Monday, Saturday, Sunday
a Period of day AM, PM
hh Two-digit hour 03, 04, 06
HH 24-hour clock 11, 14, 17
mm Two-digit minute 22, 35, 45
ss Two-digit seconds 22, 35, 45

//Custom Date and Time formatting = 2019-03-24 22:52:05
myFormat.dateFormat = "YYYY-MM-dd HH:mm:ss"
print(myFormat.string(from: currentDate))

//Get Date object from String Value
let dateString = "2019-03-24 13:12:01"
myFormat.dateFormat = "YYYY-MM-dd HH:mm:ss"
myFormat.timeZone = TimeZone.current
let newDate = myFormat.date(from: dateString)
print(newDate as Any)


No comments:

Post a Comment

NO JUNK, Please try to keep this clean and related to the topic at hand.
Comments are for users to ask questions, collaborate or improve on existing.