개발 블로그/아이폰개발
swift 상대적 시간, 1일전, 1시간 전,
snapshot
2020. 10. 20. 09:41
반응형
1 일 전,
1 시간 전,
몇 분 전,
몇 분 후,
시간 후,
일 후,
리뷰를 쓴 시간을 유저에게 보여주게 되면서 저런 시간 표현이 필요했다.
아주 간단하게..
func relativeTime(in locale: Locale = .current, unitsStyle: RelativeDateTimeFormatter.UnitsStyle = .full) -> String {
let formatter = RelativeDateTimeFormatter()
formatter.unitsStyle = unitsStyle
return formatter.localizedString(for: self, relativeTo: Date())
}
public enum UnitsStyle : Int {
case full = 0 // "2 months ago"
case spellOut = 1 // "two months ago"
case short = 2 // "2 mo. ago"
case abbreviated = 3 // "2 mo. ago"; might give different results in languages other than English
}
스타일은 이런 식으로 되어 있으니. 스타일만 변경해서 쓰면 될 것이다.
애플 문서는
developer.apple.com/documentation/foundation/relativedatetimeformatter
Apple Developer Documentation
developer.apple.com
반응형