Home 寫程式[iOS] About Date

[iOS] About Date

by 艾普利

日期格式總是讓人覺得頭痛,以下整理了幾個常用的日期格式轉換

Target Date String : “2021/06/20”


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)
}

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)
}

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"

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'

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
}

祝大家 Coding 愉快!!!

You may also like