简体   繁体   中英

How to format a date depending on the locale used?

I have a date that I would like to format depending on what country the user is from.

The date: 10th of March 2015.

Let's say the user is from USA, I'd like: 03/10/15

Let's say the user is from France, I'd like 10/03/15

I guess I could check if the locale is like en-US and fr-FR and format it accordingly but is there a way to make it automatic and for all locales?

You can use the defaultTimeZone of NSDateFormatter()

var dateFmt = NSDateFormatter()
dateFmt.timeZone = NSTimeZone.defaultTimeZone()

You can use one of the NSDateFormatter styles:

NSDateFormatterNoStyle
NSDateFormatterShortStyle 
NSDateFormatterMediumStyle
NSDateFormatterLongStyle
NSDateFormatterFullStyle

Or if you already have a format string in mind (like "MM-DD-YYYY") you can pass it through [NSDateFormatter dateFormatFromTemplate:options:locale:];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM