본문 바로가기

UIKit

Date와 DateFormatter

Date

- 날짜 및 표준 시간대와는 무관한 특정 시점

   -> 절대값의 단일 시점을 캡슐화 하는 것

- 날짜를 비교하거나, 두 날짜 사이의 시간 간격을 계산하거나, 다른 날짜를 기준과의 사이에 새로운 날짜를 만들기도 함

- DateFormatter로 위 날짜의 형태를 바꿀 수 있음

- Calendar로 달력 산술 연산이 가능

- NSDate의 중간다리 역할도 가능하여 Objective-C와 호환이 가능하도록 함

  • init() : 현재 날짜 및 시간의 값
  • init(timeIntervalSinceNow: TimeInterval) : 현재 날짜 및 시간을 기준으로 계산한 값
  • init(timeInterval: TimeInterval, since: Date) : 지정된 다른 날짜를 기준으로 계산한 값
  • init(timeIntervalSinceReferenceDate: TimeInterval) : 2001년 1월 1일 00:00:00 UTC 기준으로 계산한 값
  • init(timeIntervalSince1970: TimeInterval) : 1970년 1월 1일 00:00:00 UTC 기준으로 계산한 값
  • static var now: Date : 현재 날짜와 시간
  • static let distantFuture: Date : 먼 미래의 날짜 값
  • static let distantPast: Date : 먼 과거의 날짜 값

DateFormatter

- Date와 Text 양식 사이에서 중간다리 역할

   -> NSDate 객체의 Text 표현을 만들거나, Text를 NSDate로 변환

  • func date(from: String) -> Date?
  • func string(from: Date) -> String

- DateFormatter 종류

  • ISO8601DateFormatter : ISO 8601 형식의 날짜 표현
  • DateIntervalFormatter : NSDate 형식을 Text로 변환할 때 사용
  • DateComponentsFormatter : NSDateComponents객체 지정 시간 표현

- Style의 종류

  • .none : 연/ 월/ 일 미표시 (case 0)
  • .short : 숫자로만 짧게 연/ 월/ 일 표시 (case 1) ex. 11/23/37 or 3:30PM
  • .medium : 축약된 text로 연/ 월/ 일 표시 (case 2) ex. Nov 23, 1937 or 3:30:32PM
  • .long : 긴 text로 연/ 월/ 일 표시 (case 3) ex. November 23, 1937 or 3:30:32PM PST
  • .full : 완벽한 설명으로 연/ 월/ 일 표시 (case 4) ex. Tuesday, April 12, 1952 AD or 3:30:42 PM Pacific Standard Time

- dateStyle과 timeStyle

  • dateStyle : 날짜 표시
  • timeStyle : 시간 표시
let dateFormatter = DateFormatter()
dateFormatter.dateStyle = .medium
dateFormatter.timeStyle = .none
 
// 원하는 시간대를 설정
let date = Date(timeIntervalSinceReferenceDate: 118800)
 
// US English Locale (en_US)
// dateFormatter를 사용하여 지역 설정
dateFormatter.locale = Locale(identifier: "en_US")
// dateFormatter의 메서드를 사용하여 string으로 변환
print(dateFormatter.string(from: date)) // Jan 2, 2001
 
// French Locale (fr_FR)
dateFormatter.locale = Locale(identifier: "fr_FR")
print(dateFormatter.string(from: date)) // 2 janv. 2001
 
// Japanese Locale (ja_JP)
dateFormatter.locale = Locale(identifier: "ja_JP")
print(dateFormatter.string(from: date)) // 2001/01/02

 

 

let dateFormatter = DateFormatter()
let date = Date(timeIntervalSinceReferenceDate: 410220000)
 
// US English Locale (en_US)
dateFormatter.locale = Locale(identifier: "en_US")
// locale 세팅 후!! 원하는 Template 입력
dateFormatter.setLocalizedDateFormatFromTemplate("MMMMd")
print(dateFormatter.string(from: date)) // December 31

 

 

 

참고 링크

📒 Blog - NSDate-DateFormatter

🍎 Apple Developer - Date

🍎 Apple Developer - DateFormatter

728x90

'UIKit' 카테고리의 다른 글

UITextView  (0) 2023.08.30