[Swift] Date, DateFormatter

minsson·2022년 12월 8일
0

제가 나중에 보기 위해 정리해놓은 자료이므로 틀린 내용이 있을 수 있습니다. 댓글로 피드백 주시면 바로 수정하겠습니다. 감사합니다. ☺️ - 민쏜 -


날짜 관련 타입

  • Date
  • DateFormatter
  • Calendar (아직 안 써봄)
  • DateComponent (아직 안 써봄)

참고문서

Data Formatting Guide

⏺ Date

날짜와 시간의 한 지점을 나타내는 타입 (텍스트로 표현하고 싶다면 DateFormatter를 사용해야 한다.)

현재 날짜와 시간

Date() | Date.now
input

print(Date())
print(Date.now)

output

2022-08-20 08:32:32 +0000
2022-08-20 08:32:32 +0000

Date의 다양한 이니셜라이저

init(timeIntervalSinceNow: TimeInterval)

현재 시간으로부터 TimeInterval(초 단위) 후의 일시

let date = Date(timeIntervalSinceNow: 86400)
// 현시점으로부터 86400초 후, 즉 24시간 후

init(timeIntervalSinceReferenceDate: TimeInterval)

→ 2001년 1월 1일 00:00 기준으로 TimeInterval 만큼 후의 일시

let date = Date(timeIntervalSinceReferenceDate: 86400)
// 2001-01-02 00:00:00 +0000

init(timeIntervalSince1970: TimeInterval)

let date = Date(timeIntervalSince1970: 86400)
print(date) // 1970-01-02 00:00:00 +0000

init(timeInterval: TimeInterval, since: Date)

어떤 시점 이래로 TimeInterval 만큼 지난 후의 일시

let date = Date(timeInterval: 86400, since: Date(timeIntervalSinceNow: 86400))

현재 일시: 2022-08-20 10:20:43 +0000
86400초 후: 2022-08-21 10:20:43 +0000
86400초 후로부터 86400초 후: 2022-08-22 10:20:43 +0000

⏺ DateFormatter | 날짜 <-> String

Date 타입과 String의 타입을 변환시키고, Formatting을 담당하는 객체

DateDateFormatter 타입을 인스턴스화해 사용하고, dateStyle, timeStyle, locale, dateFormat을 사용해 Date를 표시할 형식을 지정한다.

String을 Date로 형변환하는 경우에는, 형식이 맞지 않으면 nil이 반환된다.

날짜와 String을 서로 치환하는 법 ⭐️

func date(from: String) -> Date?
Returns a date representation of a specified string that the system interprets using the receiver’s current settings.

func string(from: Date) -> String
Returns a string representation of a specified date that the system formats using the receiver’s current settings.

class func localizedString(from: Date, dateStyle: DateFormatter.Style, timeStyle: DateFormatter.Style) -> String
Returns a string representation of a specified date, that the system formats for the current locale using the specified date and time styles.

func getObjectValue(AutoreleasingUnsafeMutablePointer<AnyObject?>?, for: String, range: UnsafeMutablePointer?)
Returns by reference a date representation of a specified string and its date range, as well as a Boolean value that indicates whether the system can parse the string.

활용사례: 주어진 TimeInterval을 원하는 서식의 String으로 변경하기 (Diary 프로젝트 활용)

input

extension TimeInterval {
    func localizedFormat() -> String {
        let formattedDate = Date(timeIntervalSince1970: self)

        let dateFormatter: DateFormatter = {
            let dateFormatter = DateFormatter()
            dateFormatter.locale = Locale(identifier: "ko_KO")
            dateFormatter.dateStyle = .long

            return dateFormatter
        }()

        return dateFormatter.string(from: formattedDate)
    }
}

let today = Date().timeIntervalSince1970.localizedFormat()
print(today)

output

2022820

DateFormatter.Style

The format for these date and time styles is not exact because they depend on the locale, user preference settings, and the operating system version. Do not use these constants if you want an exact format.
유저의 세팅에 따라 달라질 수 있으므로, 정확한 포멧을 원할 경우에는 사용하지 말 것!
프로젝트를 하면서 이상한 결과가 나온 적이 있는데, 이것 때문인 것 같다.
.none
.short
.medium
.long
.full

Date Format 종류

Date Format in Swift

This may be useful for who want to use dateformater.dateformat;
if you want 12.09.18 you use dateformater.dateformat = "dd.MM.yy"

Wednesday, Sep 12, 2018           --> EEEE, MMM d, yyyy
09/12/2018                        --> MM/dd/yyyy
09-12-2018 14:11                  --> MM-dd-yyyy HH:mm
Sep 12, 2:11 PM                   --> MMM d, h:mm a
September 2018                    --> MMMM yyyy
Sep 12, 2018                      --> MMM d, yyyy
Wed, 12 Sep 2018 14:11:54 +0000   --> E, d MMM yyyy HH:mm:ss Z
2018-09-12T14:11:54+0000          --> yyyy-MM-dd'T'HH:mm:ssZ
12.09.18                          --> dd.MM.yy
10:41:02.112                      --> HH:mm:ss.SSS
dateFormatter.dateFormat = "hh:mm:ss a 'on' MMMM dd, yyyy"
//Output: 12:16:45 PM on January 01, 2000

dateFormatter.dateFormat = "E, d MMM yyyy HH:mm:ss Z"
//Output: Sat, 1 Jan 2000 12:16:45 +0600

dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"
//Output: 2000-01-01T12:16:45+0600

dateFormatter.dateFormat = "EEEE, MMM d, yyyy"
//Output: Saturday, Jan 1, 2000

dateFormatter.dateFormat = "MM-dd-yyyy HH:mm"
//Output: 01-01-2000 12:16

dateFormatter.dateFormat = "MMM d, h:mm a"
//Output: Jan 1, 12:16 PM

dateFormatter.dateFormat = "HH:mm:ss.SSS"
//Output: 12:16:45.000

dateFormatter.dateFormat = "MMM d, yyyy"
//Output: Jan 1, 2000

dateFormatter.dateFormat = "MM/dd/yyyy"
//Output: 01/01/2000

dateFormatter.dateFormat = "hh:mm:ss a"
//Output: 12:16:45 PM

dateFormatter.dateFormat = "MMMM yyyy"
//Output: January 2000

dateFormatter.dateFormat = "dd.MM.yy"
//Output: 01.01.00

//Customisable AP/PM symbols

dateFormatter.amSymbol = "am"
dateFormatter.pmSymbol = "Pm"
dateFormatter.dateFormat = "a"

기타 형식

  • era: G (AD), GGGG (Anno Domini)
  • year: y (2018), yy (18), yyyy (2018)
  • month: M, MM, MMM, MMMM, MMMMM
  • day of month: d, dd
  • day name of week: E, EEEE, EEEEE, EEEEEE

input

let dateFormatterGet = DateFormatter()
dateFormatterGet.dateFormat = "yyyy-MM-dd HH:mm:ss"

let dateFormatterPrint = DateFormatter()
dateFormatterPrint.dateFormat = "MMM dd,yyyy"

if let date = dateFormatterGet.date(from: "2016-02-29 12:24:26") {
    print(dateFormatterPrint.string(from: date))
} else {
   print("There was an error decoding the string")
}

output

229,2016
profile
풋사과 iOS 개발자

0개의 댓글