본문 바로가기

iOS/STUDY

[iOS] Format the Date and Time

https://developer.apple.com/tutorials/app-dev-training/displaying-cell-info

 

Apple Developer Documentation

 

developer.apple.com

 

Apple UIKit 튜토리얼 배운 것을 공부하여 정리하였습니다.

 

우선 배운 것을 정리하면 Foundation 프레임워크를 사용하고

해당하는 장소에 따라 시간을 비교하여 오늘인지 아닌지,

오늘이라면 'Today', 오늘이 아니라면 'Mar 8' 이렇게 나타내는 방법을 배웠습니다.

 

Foundation 프레임워크의 Date 구조체를 extension해서

dayAndTimeText String 변수를 만들었습니다.

 

dayAndTimeText

extension Date {
	var dayAndTimeText: String {
    	// 반환값: Today at time, Date at time
    }
}

1. 시간은 언제인지 - formatted 을 사용하여 String 으로 구해보자

func formatted(date: Date.FormatStyle.DateStyle, time: Date.FormatStyle.TimeStyle) -> String

 

Converts `self` to its textual representation that contains both the date and time parts. The exact format depends on the user's preferences.

`self`를 날짜와 시간 부분을 모두 포함하는 텍스트 표현으로 변환합니다. 정확한 형식은 사용자의 기본 설정에 따라 다릅니다.

 

공식문서에는 딱히 설명이 없어 definition을 찾아보았습니다. 

이 함수가 Date 의 extension 내에 정의된 것을 보면 현재 날짜 = self 를 저희가 정한 형식으로 String 을 반환해준다고 합니다.

그렇다면 date 날짜는 오늘인지 아닌지에 따라서 달라지기 때문에 시간 String만 얻어야합니다.

 

Date.FormatStyle.DateStyle 에는 여러가지 스타일이 있는데 .omitted 를 사용하면 date를 생략할 수 있습니다.

.abbreviated 는 축약하여 쓰는 형태입니다. ex) "Oct 21, 2015"

.complete  ex) "Wednesday, October 21, 2015"

.long  ex) "October 21, 2015"

.numeric  ex) "10/21/2015"

 

Date.FormatStyle.TimeStyle 에도 여러가지 스타일이 있습니다.

여기서는 .shortened 를 사용하여  ex) 04:29 PM, 16:29 형식으로 나타내었습니다.

.omitted  ex) 똑같이 time을 생략할 수 있습니다.

.complete  ex) 4:29:24 PM PDT, 16:29:24 GMT

.standard  ex) 4:29:24 PM, 16:29:24

 

오후 4시인지 16시 인지는 어떻게 골라야할지 모르겠는데,, 아이폰 설정을 따라가는 것일까요? Umm...

let timeText = formatted(date: .omitted, time: .shortened)

이렇게 시간 String을 만들었습니다.

 

 

2. 오늘인지, 오늘이 아니라면 날짜가 몇일인지

Locale.current.calendar.isDateInToday(self)

Foundation 프레임워크에 Locale 이라는 구조체가 있습니다.

Information about linguistic, cultural, and technological conventions for use in formatting data for presentation.

언어, 문화, 기술 협약 및 표준에 대한 정보를 가지고 있다고 합니다

 

// Locale struct
/// Returns the user's current locale.
public static var current: Locale { get }

/// Returns the calendar for the locale, or the Gregorian calendar as a fallback.
public var calendar: Calendar { get }



/// Returns `true` if the given date is within today, as defined by the calendar and calendar's locale.
///
/// - parameter date: The specified date.
/// - returns: `true` if the given date is within today.
@available(iOS 8.0, *)
public func isDateInToday(_ date: Date) -> Bool

 

오늘인지 아닌지 ^0^

var dayAndTimeText: String {
    let timeText = formatted(date: .omitted, time: .shortened)
    // '오늘 오후 3시' 에서 오늘을 맡고있습니다.
    if Locale.current.calendar.isDateInToday(self) {
        let timeFormat = NSLocalizedString("Today at %@", comment: "Today at time format string")
        return String(format: timeFormat, timeText)
    } else {
        let dateText = formatted(.dateTime.month(.abbreviated).day())
        let dateAndTimeFormat = NSLocalizedString("%@ at %@", comment: "Date and Time format string")
        return String(format: dateAndTimeFormat, dateText, timeText)
    }
}

 

이렇게 코드가 완성이 되었는데 timeText 를 그냥 "Today at" + timeText 를 하지않고 String format 을 만들어서 반환했네요..!

 

1. NSLocalizedString

Returns a localized string from a table that Xcode generates for you when exporting localizations.
func NSLocalizedString(_ key: String, 
			tableName: String? = nil, 
			bundle: Bundle = Bundle.main,
                        value: String = "",
                        comment: String) -> String

key 값과 comment 값은 필수입니다. comment 는 주석값!

 

%d - int

%f - float

%ld - long

%@ - string value and for many more

 

순간 쓰다가 이해가 안가서 Localizing 을 다시 찾아보았습니다 ㅋㅋ... 위에서  "Today at" + timeText  을 하지 않은 이유..

지역마다 달라야 하니까..!!

처음부터 Locale을 적용하겠다고 말하고 있었는데 이해를 못하고 코드를 짜고 있었네요..!!

localizing은 아래 블로그에서 자세히 설명해주니 의미만 알고 넘어가겠습니다ㅎ.ㅎ

 

 

2. String - format 사용

 

timeFormat 을 NSLocalizedString 로 만들어서 String으로 반환해 줍니다.

 

String

init(format: String, _ arguments: CVarArg...)

%@ 이 곳에 저 arguments 들을 넣어서 String을 생성할 수 있습니다.

 

 

 

 

참조

https://zeddios.tistory.com/744

 

iOS ) NSLocalizedString with variables

안녕하세요 :) Zedd입니다. 로컬라이징을 생각하고있는데 갑자기 궁금증이 들어서 글을 쓰게되었... 만약에 음..막 “방금 전”이런건 괜찮지만 “10분 전”이런거는 로컬라이징 어떻게 할까요??

zeddios.tistory.com

https://zeddios.tistory.com/368

 

iOS ) 왕초보를 위한 로컬라이징 / Localizing Your App

안녕하세요 :) Zedd입니다. 오늘은 로컬라이징!!!!! 저는 영어를 베이스로 만들고 있는데..물론 다 이해가지만 각 나라언어로 보여지면 어떨까 싶어서 이번기회에 로컬라이징을 공부해보려고 합니

zeddios.tistory.com

 

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

[iOS] Identifiable 프로토콜  (0) 2022.03.10
[iOS] extension + Generic where  (0) 2022.03.08
[iOS] UICollectionViewDiffableDataSource  (0) 2022.03.05
[iOS] UICollectionViewLayout  (0) 2022.03.04
[Swift] @escaping  (0) 2022.02.28