새소식

iOS/Swift

[Swift] Date / DateFormatter

  • -
 

Date | Apple Developer Documentation

A specific point in time, independent of any calendar or time zone.

developer.apple.com

 

Date


날짜와 시간을 다루기 위해 기본적으로 필요한 Date함수

// 현재 시간 출력
let currentDate = Date() 
print(currentDate) // 2023-07-15 05:31:36 +0000

// Unix 시간(1970년 1월 1일 00:00:00 UTC)
let unixDate = Date().timeIntervalSince1970
print(unixDate) //1689403952.721513

// 현재 시간에서 60초(1분)이후
let 1minAfterDate = Date(timeIntervalSinceNow: 60)

 

 

현재 날짜를 알아볼 수 있었는데 내가 원하는 형식으로 출력하고 할 때 DateFormatter를 사용

 

DateFormatter | Apple Developer Documentation

A formatter that converts between dates and their textual representations.

developer.apple.com

 

 

 

DateFormatter


Date에서 Text형식으로 변환할 때 사용하며, 내가 원하는 방식으로 변환이 가능함

 

let currentDate = Date()
let dateFormatter = DateFormatter()

// Date 표현 방식 설정
dateFormatter.dateFormat = "yyyy/MM/dd"

// 시간 기준 설정
dateFormatter.locale = Locale(identifier: "ko") // 한국 시간 기준

// Date to String
let dateString = dateFormatter.string(from: currentDate)
print(dateString) // 2023/07/15

// String to Date
let test = "2023/07/01"
let stringDate = dateFormatter.date(from: test) // "Jul 1, 2023 at 12:00 AM"

 

dateFormat은 여기서 확인할 수 있다.

 

NSDateFormatter.com - Live Date Formatting Playground for Swift

Ben is an experienced software developer from Houston, TX. He is the founder of NSScreencast, where you can find over 500 screencasts on iOS development topics. You can find Ben on Twitter or his blog.

nsdateformatter.com

 

참고

https://leeari95.tistory.com/30

 

728x90

'iOS > Swift' 카테고리의 다른 글

[Swift] User Notifications  (0) 2023.08.06
[Swift] @discardableResult  (0) 2023.07.26
[Swift] UserDefault  (0) 2023.07.15
[Swift] Task, await, async  (0) 2023.05.20
[Swift] NotificationCenter  (0) 2023.04.16
Contents

포스팅 주소를 복사했습니다

이 글이 도움이 되었다면 공감 부탁드립니다.