Skip to content

Instantly share code, notes, and snippets.

@Bersaelor
Last active February 8, 2016 10:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Bersaelor/0df3e7be7aaab2536ef3 to your computer and use it in GitHub Desktop.
Save Bersaelor/0df3e7be7aaab2536ef3 to your computer and use it in GitHub Desktop.
Demonstrates localized NSDateFormatter behaviour
//: Playground - noun: a place where people can play
import UIKit
let date = NSDate()
let number = 29.23
let heightInm = 1.87
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy"
print("default locale: \(dateFormatter.locale.localeIdentifier)")
print(dateFormatter.stringFromDate(NSDate()))
let numberFormatter = NSNumberFormatter()
numberFormatter.maximumFractionDigits = 2
let currencyFormatter = NSNumberFormatter()
currencyFormatter.numberStyle = NSNumberFormatterStyle.CurrencyStyle
let localizedDateFormatter = NSDateFormatter()
localizedDateFormatter.dateFormat = NSDateFormatter.dateFormatFromTemplate("yyyy", options: 0,
locale: NSLocale.currentLocale())
let lengthFormatter = NSLengthFormatter()
lengthFormatter.forPersonHeightUse = true
//current locale, saudi arabia, urdu/india
let locales = [NSLocale.currentLocale().localeIdentifier, "de_DE", "ar_SA", "ur_IN", "zh_HANS"]
var years = [String]()
var numbers = [String]()
var moneys = [String]()
var bodyHeights = [String]()
for localeID in locales {
//even better, with dateFormatFromTemplate
localizedDateFormatter.locale = NSLocale(localeIdentifier: localeID)
numberFormatter.locale = NSLocale(localeIdentifier: localeID)
lengthFormatter.numberFormatter.locale = NSLocale(localeIdentifier: localeID)
currencyFormatter.locale = NSLocale(localeIdentifier: localeID)
years += [localizedDateFormatter.stringFromDate(date)]
numbers += [numberFormatter.stringFromNumber(number) ?? ""]
moneys += [currencyFormatter.stringFromNumber(number) ?? ""]
bodyHeights += [lengthFormatter.stringFromMeters(heightInm)]
}
print(years) //"["2016", "2016", "١٤٣٧", "۲۰۱۶", "2016"]"
print(numbers) //"["29.23", "29,23", "٢٩٫٢٣", "۲۹.۲۳", "29.23"]"
print(bodyHeights) //"["6 ft, 1.622 in", "187 cm", "١٨٧ سم", "۱۸۷ سینٹی میٹر", "187厘米"]\n"
print(moneys) //"["$29.23", "29,23 €", "٢٩٫٢٣ ر.س.‏", "₹ ۲۹.۲۳", "¤ 29.23"]\n"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment