swiftnsdatensdatecomponentsformatter

How to set DateComponentFormatter's local other than current?


Situation

I have a function that uses DateComponentFormatter's function fun string(from: Date, to: Date) to return a formatted string based on the time difference between two dates and it works perfectly. However I want to return this formatted string always in English (currently formatting according to device's local).

Questions

How do you set the DateComponentFormatter's local like what you can do with DateFormatter's? If you can't, how would you proceed?

Code:

import Foundation

func returnRemainingTimeAsString(currentDate: Date, nextDate: Date)->String {

  let dateComponentsFormatter = DateComponentsFormatter()
  dateComponentsFormatter.unitsStyle = DateComponentsFormatter.UnitsStyle.full
  dateComponentsFormatter.allowedUnits = [.day, .hour, .minute, .second]
  dateComponentsFormatter.maximumUnitCount = 1

  let differenceAsString = dateComponentsFormatter.string(from: currentDate, to: nextDate)!

  return differenceAsString
}

let currentDate = Date()
let futureDate = currentDate.addingTimeInterval(3604)
returnRemainingTimeAsString(currentDate: currentDate, nextDate: futureDate)

// prints 1 hour (if devices local is English) or 1 hora (if Spanish),
// and I want it to return always 1 hour.

Solution

  • DateComponentsFormatter has a calendar property.

    Get the current calendar, set its locale and assign the calendar to the formatter.

    let dateComponentsFormatter = DateComponentsFormatter()
    var calendar = Calendar.current
    calendar.locale = Locale(identifier: "en_US_POSIX")
    dateComponentsFormatter.calendar = calendar
    dateComponentsFormatter.unitsStyle = .full
    ...