관리 메뉴

김종권의 iOS 앱 개발 알아가기

[iOS - swift] Date(), 시분초, 날짜, 시간 파싱의 모든 것, seconds to Date (Date, Calendar, ISO8601, UTC) 본문

iOS 응용 (swift)

[iOS - swift] Date(), 시분초, 날짜, 시간 파싱의 모든 것, seconds to Date (Date, Calendar, ISO8601, UTC)

jake-kim 2022. 1. 25. 23:23

알아야하는 Date 형식

  • swift에서 제공하는 DateDecodingStrategy 종류 파악
    • deferredToDate (default 형식) - 애플만이 가지고 있는 형식 (ISO8601과 유사)
      년-월-일 시:분:초 +TimeZone
      Date() // 2022-01-25 00:53:06 +0000​
    • secondsSince1970: UTC 형식 (1972년 1월 1일부터로부터 몇초가 경과했는지)
    • iso8601은 아래와 같은 형식
      Date().ISO8601Format() // 2022-01-25T00:53:06Z​


참고) Time Zone의 의미

Time Zone은 UTC의 offset을 의미하며 특정 지역시간이 다른 경우 offset값을 표현

- 보통 숫자로 +0000 처럼 표현

- 'Z'와 같이 알파벳을 포현하는 경우, "zone designator"라고 하며 Z는 +0000을 의미

// swift에서 표현 방식
2022-01-25 00:53:06 +0000​ // default
2022-01-25T00:53:06Z // ISO8601

// 일반적인 표현 방식
2016-10-27T17:13:40+00:00
2016-10-27T17:13:40Z

Swift의 Date()

  • 위에서 살펴본 대로 swift의 default 형식은 deferredToDate 형식
print(Date()) // 2022-01-25 12:41:07 +0000
  • Date 형식을 시,분,초로 파싱하는 방법
    • Calender 사용하여 DateComponent 타입으로 변환
      let currentDate = Date()
      print(currentDate) // 2022-01-25 12:53:06 +0000
      let dateComponent = Calendar.current.dateComponents([.hour, .minute, .second], from: currentDate)
      
      // dateComponent DateComponent 타입
      print(dateComponent) // hour: 22 minute: 11 second: 4 isLeapMonth: false​
    • hour만 접근
      // Int? 형
      print(parsedDate.hour) // 22​
  • 서버에서 Date() 형식으로 내려주었을때, 현재 시간으로부터 차이를 구하여 남은 시간, 분, 초 얻는 방법
    • timeIntervalSince(_:)를 사용하여 시간차 획득
      let currentDate = Date()
      let expirationDate = currentDate.addingTimeInterval(4810) // 1시간 20분 10초
      let remainUTC = expirationDate.timeIntervalSince(currentDate) // TimeInterval 형태 (UTC)
    • 시간차는 TimeInterval 형으로 "초"로 나오기 때문에, 이 값을 각각 hour, minute, seconds로 변환
      extension Int {
        var hour: Int {
          self / 3600
        }
        var minute: Int {
          (self % 3600) / 60
        }
        var seconds: Int {
          (self % 60)
        }
      }
      
      let remainUTCInteger = Int(remainUTC)
      print(remainUTCInteger.hour) // 1 시간
      print(remainUTCInteger.minute) // 20 분
      print(remainUTCInteger.seconds) // 10 초​

* 시간 차이를 구하여 시,분,초 구하기 전체 코드

import UIKit

class ViewController: UIViewController {
  
  override func viewDidLoad() {
    super.viewDidLoad()
    
    let currentDate = Date()
    let expirationDate = currentDate.addingTimeInterval(4810) // 1시간 20분 10초
    let remainUTC = expirationDate.timeIntervalSince(currentDate) // TimeInterval 형태 (UTC)
    let remainUTCInteger = Int(remainUTC)
    print(remainUTCInteger.hour) // 1 시간
    print(remainUTCInteger.minute) // 20 분
    print(remainUTCInteger.seconds) // 10 초
  }
}

extension Int {
  var hour: Int {
    self / 3600
  }
  var minute: Int {
    (self % 3600) / 60
  }
  var seconds: Int {
    (self % 60)
  }
}

* 참고

https://ko.wikipedia.org/wiki/ISO_8601

https://www.hackingwithswift.com/articles/119/codable-cheat-sheet

Comments