standousset
standousset

Reputation: 1161

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.

Upvotes: 5

Views: 5516

Answers (2)

Rob
Rob

Reputation: 437582

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.

Upvotes: 1

vadian
vadian

Reputation: 285082

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
...

Upvotes: 11

Related Questions