Swift DateFormatter [Swift] 사용자의 날짜 및 시간포맷 사용하기

[Swift] 사용자의 날짜 및 시간포맷 사용하기

Device - 설정 - 날짜 및 시간에 설정에 따라 Date를 보여줘야하는 요구사항을 받았다.
DateFormatter를 사용하면 이를 해결 가능하다.

Image

let dateFormatter = DateFormatter()
dateFormatter.dateStyle = .medium

위의 코드는 시스템 format 형태로 output 이 나오기 때문에 커스터마이징이 어렵다. 복잡한 요구사항인 경우 포맷 자체를 검사해 해결할 수 있다.
하단의 코드를 활용하여 “a HH” 또는 “hh” 포맷인지 확인할 수 있다.

extension Date {
  func systemStyleHourString() -> String? {
      guard
          let dateFormat = DateFormatter.dateFormat(fromTemplate: "j",
                                                    options: 0,
                                                    locale: .current)
      else { return nil }
      
      let dateFormatter = DateFormatter()
      dateFormatter.dateFormat = dateFormat
      return dateFormatter.string(from: self)
  }
}

댓글남기기