4

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.
rmaddy
  • 314,917
  • 42
  • 532
  • 579
standousset
  • 1,092
  • 1
  • 10
  • 25

2 Answers2

10

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
...
vadian
  • 274,689
  • 30
  • 353
  • 361
  • What is the locale for ? identifier: "en_US_POSIX" –  Dec 09 '19 at 17:15
  • 1
    @Farhadam `en_US_POSIX` is *a locale that's specifically designed to yield US English results regardless of both user and system preferences*. See [Technical Q&A QA1480](https://developer.apple.com/library/archive/qa/qa1480/_index.html) – vadian Dec 09 '19 at 17:24
0

For the formatter to show localized strings, you have to specify the supported locales in the target settings.

enter image description here

If the device’s current locale is one of the locales supported in the target settings, you will get the localized date components without needing to manually set the calendar of the formatter. You only need to do that if you want a locale other than the device’s current locale.

Rob
  • 415,655
  • 72
  • 787
  • 1,044