简体   繁体   中英

NSDateFormatter gives different values on device and simulator? What is work around?

I am using NSDateFormatter, the problem is with its consistency. If I use the kCFDateFormatterMediumStyle it gives the format as "Nov 26, 2009" in simulator but on device it gives "26-Nov-2009".

Now I have the question, Is this NSFormatter trustable means in near future or updates from apple can it change the style again?

While the other answer mentioned above is technically correct, it doesn't give you the solution you are looking for. While the NSDateFormatter defaults to using user locales (and is, as such, not going to give you useful results) you can request a specific locale to get consistent results:

NSDateFormatter *frm = [[NSDateFormatter alloc] init];
[frm setDateFormat:@"EEE MMM dd HH:mm:ss ZZZ yyyy"];

NSLocale *en_US = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US"];
[frm setLocale:en_US];
[en_US release];

NSDateFormatter formats the date to the user's preference, based on the International settings on the device. As such you can never expect this string to be consistent because of the amount of different ways that dates are displayed across the world.

I've found the best way to format a date as a string (to use to give to webservers etc) is to use NSDateComponents and convert these to strings.

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