#Swift에서 경과 시간을 간단히 표시하는 방법

21315 단어 Swifttech

하고 싶은 일



트위터 기고일 등 지금부터 얼마 전부터 트위터의 날짜차가 있었는지 표시한다.여기 목표는 한 단위만 표시하는 거예요.
다음 클래스 사용
  • Date
  • DateComponents
  • DateComponentsFormatter
  • Calendar
  • 이루어지다


    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에도 미묘해 보이는 점이 있기 때문에 개선된 점이 있으면 평어로 말씀해 주세요.

    좋은 웹페이지 즐겨찾기