NSDateFormatter not working as it should when region is set to Asian regions…

Discussion in 'iOS Programming' started by cstromme, Mar 31, 2010.

  1. cstromme macrumors regular

    Joined:
    Feb 26, 2007
    #1
    Have the following piece of code in my app:

    Code:
    NSDate *today = [NSDate date];
    NSDateFormatter *outputDateFormatter = [[NSDateFormatter alloc] init];
    [outputDateFormatter setDateFormat:@"yyyy"];
    NSString *year = [outputDateFormatter stringFromDate:today];
    
    [outputDateFormatter setDateFormat:@"yyyy-MM/dd' 'hh:mmaa"];
    NSDate *datetime = [outputDateFormatter dateFromString:[NSString stringWithFormat:@"%@-%@",year,tmpLastPostDate]];
    NSLog(@"DateFormat: %@\nString: %@\nDate: %@",[outputDateFormatter dateFormat],[NSString stringWithFormat:@"%@-%@",year,tmpLastPostDate],datetime);
    
    NSLog(@"Pre: %@",tmpLastPostDate);
    [outputDateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:SSSSSS"];
    tmpLastPostDate = [outputDateFormatter stringFromDate:datetime];
    NSLog(@"Post: %@",tmpLastPostDate);
    [outputDateFormatter release];
    All the NSLog statements are added to try and work out the problem here. What this does is take my input date, which is of format '3/29 8:48pm', add the year to the string and then run it through the formatter to output it in the 'yyyy-MM-dd'T'HH:mm:SSSSSS' format. This all works perfectly in all cases except when the device's regional setting has been set to Japan. For some reason then the 'NSDate *datetime = [outputDateFormatter dateFromString:[NSString stringWithFormat:mad:"%@-%@",year,tmpLastPostDate]];' just gives me a nil datetime.

    Here's the output from the NSLog statement on the line below:

    Again, this works perfectly for any other region I've tested other than some of the Asian ones.

    So what is wrong here? Is this a bug in NSDateFormatter or am I doing something wrong? I am specifically telling it what format it should be expecting the date in, so why is this being affected by the region setting?
     
  2. bredell macrumors regular

    Joined:
    Mar 30, 2008
    Location:
    Uppsala, Sweden
    #2
    You're forgetting that the strings "AM" and "PM" are also localized. If you set the regional setting to Japan you can't use the time string "11:36pm", you have to use the japanese variant "11:36午後".

    In your code you're forcing people to use a certain date and time format which is generally a bad thing, people should be able to use their own local format.
     

Share This Page