#Swift에서 경과 시간을 간단히 표시하는 방법
하고 싶은 일
트위터 기고일 등 지금부터 얼마 전부터 트위터의 날짜차가 있었는지 표시한다.여기 목표는 한 단위만 표시하는 거예요.
다음 클래스 사용
이루어지다
extension Calendar {
public func durationString(candidate components: [Calendar.Component], style unitsStyle: DateComponentsFormatter.UnitsStyle = .abbreviated, from start: Date, to end: Date) -> String? {
for component in components {
let dateComponents = self.dateComponents([component], from: start, to: end)
if let time = dateComponents.getTime(with: component) {
if time > 0 {
let formatter = DateComponentsFormatter()
formatter.allowedUnits = component.unit
formatter.unitsStyle = unitsStyle
formatter.calendar = self
return formatter.string(from: dateComponents)
}
}
}
return nil
}
}
extension DateComponents {
public func getTime(with component: Calendar.Component) -> Int? {
switch component {
case .second: return second
case .era: return era
case .year: return year
case .month: return month
case .day: return day
case .hour: return hour
case .minute: return minute
case .weekday: return weekday
case .weekdayOrdinal: return weekdayOrdinal
case .quarter: return quarter
case .weekOfMonth: return weekOfMonth
case .weekOfYear: return weekOfYear
case .yearForWeekOfYear: return yearForWeekOfYear
case .nanosecond: return nanosecond
default:
fatalError()
}
}
}
extension Calendar.Component {
public var unit: NSCalendar.Unit {
switch self {
case .second: return .second
case .era: return .era
case .year: return .year
case .month: return .month
case .day: return .day
case .hour: return .hour
case .minute: return .minute
case .weekday: return .weekday
case .weekdayOrdinal: return .weekdayOrdinal
case .quarter: return .quarter
case .weekOfMonth: return .weekOfMonth
case .weekOfYear: return .weekOfYear
case .yearForWeekOfYear: return .yearForWeekOfYear
case .nanosecond: return .nanosecond
case .calendar: return .calendar
case .timeZone: return .timeZone
@unknown default:
fatalError()
}
}
}
테스트 코드
var calendar = Calendar.current
calendar.locale = .init(identifier: "ja_JP")
let now = Date()
let oneDayAgo: Date = {
var components = DateComponents()
components.day = -1
return calendar.date(byAdding: components, to: now)!
}()
let oneHourAgo: Date = {
var components = DateComponents()
components.hour = -1
return calendar.date(byAdding: components, to: now)!
}()
let oneMinuteAgo: Date = {
var components = DateComponents()
components.minute = -1
return calendar.date(byAdding: components, to: now)!
}()
let oneSecondAgo: Date = {
var components = DateComponents()
components.second = -1
return calendar.date(byAdding: components, to: now)!
}()
let candidates: [Calendar.Component] = [.day, .hour, .minute, .second]
let dayDuration = calendar.durationString(candidate: candidates, from: oneDayAgo, to: now)
// "1日"
let hourDuration = calendar.durationString(candidate: candidates, from: oneHourAgo, to: now)
// "1時間"
let minuteDuration = calendar.durationString(candidate: candidates, from: oneMinuteAgo, to: now)
// "1分"
let secondDuration = calendar.durationString(candidate: candidates, from: oneSecondAgo, to: now)
// "1秒"
총결산
Calendar의 extension으로 구현되면 Locale를 설정할 수도 있습니다.
보아하니 같다
Calendar.Component
변환만extension에도 미묘해 보이는 점이 있기 때문에 개선된 점이 있으면 평어로 말씀해 주세요.
Reference
이 문제에 관하여(#Swift에서 경과 시간을 간단히 표시하는 방법), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://zenn.dev/zunda_pixel/articles/d6b0eb07187df0텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
우수한 개발자 콘텐츠 발견에 전념 (Collection and Share based on the CC Protocol.)