Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 691
Madhup Singh Yadav Avatar asked Nov 26 '09 11:11

Madhup Singh Yadav


2 Answers

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];
like image 130
Douglas Mayle Avatar answered Oct 03 '22 05:10

Douglas Mayle


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.

like image 33
Daniel Tull Avatar answered Oct 03 '22 06:10

Daniel Tull