[Swfit] About Date

戴萌
2 min readJun 20, 2021

Date String : “2021/06/20”

  1. String to Date
func convertStringToDate(str: String) -> Date? {
let formatter = DateFormatter()
formatter.locale = Locale.current
formatter.timeZone = TimeZone.current
formatter.dateFormat = "yyyy/mm/dd"
return formatter.date(from: str)
}

2. Date to String

func convertDateToString(date: Date) -> String? {
let formatter = DateFormatter()
formatter.locale = Locale.current
formatter.timeZone = TimeZone.current
formatter.dateFormat = "yyyy/mm/dd"
return formatter.string(from: date)
}

3. Relative Date

func relativeDate(date: Date) -> String {
let formatter = RelativeDateTimeFormatter()
formatter.locale = Locale.current
return formatter.localizedString(for: date, relativeTo: Date())
}
//return value will be "2 hour age" or "2 day age"

4. Convert ISO8601

  • year, month, day, as “XXXX-XX-XX”
  • “T” as a separator
  • hour, minute, seconds, milliseconds, as “XX:XX:XX.XXX”.
  • “Z” as a zone designator for zero offset, a.k.a. UTC, GMT, Zulu time.

Format : 2021–06–20T10:00:05Z

yyyy-MM-dd'T'HH:mm:ss'Z'

  • String to date
func convertStringToISO8601Date(str: String) -> Date? {
let dateFormatter = ISO8601DateFormatter()
var date = dateFormatter.date(from: str)
return dateFormatter.date(from: self)
}
  • date to String
func convertStringToISO8601Date(date: Date) -> String? {
let dateFormatter = ISO8601DateFormatter()
var date = dateFormatter.date(from: str)
return dateFormatter.string(from: date)
}

Format : 2021–06–20T10:00:05.000Z

yyyy-MM-dd'T'HH:mm:ss.SSS'Z'

Add Options [.withInternetDateTime, .withFractionalSeconds]

  • String to date
func convertStringToISO8601Date(str: String) -> Date? {
let dateFormatter = ISO8601DateFormatter()
dateFormatter.formatOptions = [.withInternetDateTime, .withFractionalSeconds]
var date = dateFormatter.date(from: str)
return dateFormatter.date(from: self)
}
  • date to String
func convertStringToISO8601Date(date: Date) -> String? {
let dateFormatter = ISO8601DateFormatter()
dateFormatter.formatOptions = [.withInternetDateTime, .withFractionalSeconds]
var date = dateFormatter.date(from: str)
return dateFormatter.string(from: date)
}

Combination

  • String to date
func convertStringToISO8601Date(str: String) -> Date? {
let dateFormatter = ISO8601DateFormatter()
var date = dateFormatter.date(from: self)
if date == nil {
dateFormatter.formatOptions = [.withInternetDateTime, .withFractionalSeconds]
date = dateFormatter.date(from: str)
}
return date
}

--

--