Search code examples
iosdatensdateformatter

Date format conversion issue with NSDateFormatter


I'm doing the following code:

NSString *stringToFormat = ticket.date;
NSDateFormatter *df = [[NSDateFormatter alloc] init];
[df setDateFormat:@"dd MMMM yyyy"];

df.locale = [[NSLocale alloc] initWithLocaleIdentifier: @"ro_RO"];
[df setDateFormat:@"dd.MM.yyyy"];
NSString *final = [df stringFromDate:[df dateFromString:stringToFormat]];
self.dateLabel.text = final;

The problem is that final is nil? Why?


Solution

  • Two issues in your code:

    1. You are using the same instance of date formatter with two different date format.
    2. You have wrong date format set to fit your input date.

    Here is corrected code:

    NSString *stringToFormat = @"16.Octombrie.2015 10:02";
    
    NSDateFormatter *df = [[NSDateFormatter alloc] init];
    df.locale = [[NSLocale alloc] initWithLocaleIdentifier: @"ro_RO"];
    [df setDateFormat:@"dd.MMMM.yyyy hh:mm"];
    
    NSDateFormatter *df2 = [[NSDateFormatter alloc] init];
    df2.locale = [[NSLocale alloc] initWithLocaleIdentifier: @"ro_RO"];
    [df2 setDateFormat:@"dd.MM.yyyy"];
    
    NSString *final = [df2 stringFromDate:[df dateFromString:stringToFormat]];
    

    You have to also set locale to first date formatter to let formatter recognise Octombrie as valid month.