Converting NSString into NSDate in objective c for mention Date String

36 views Asked by At

I am trying to convert DateString into Different DateFromat.

    strDate = @"24-08-2022 06:38:50 +0:00"

    NSDateFormatter *dateformate = [[NSDateFormatter alloc] init];
    
    [dateformate setTimeZone:[NSTimeZone localTimeZone]];
    [dateformate setLocale:[NSLocale localeWithLocaleIdentifier:@"en_US_POSIX"]];
    
    [dateformate setDateFormat:@"dd-MM-yyyy HH:mm:ss Z"];
    NSLog(@"%@", [dateformate dateFromString:strDate]);
    [dateformate setDateFormat:@"dd-MM-yyyy HH:mm:ss ZZ"];
    NSLog(@"%@", [dateformate dateFromString:strDate]);
    [dateformate setDateFormat:@"dd-MM-yyyy HH:mm:ss ZZZ"];
    NSLog(@"%@", [dateformate dateFromString:strDate]);
    [dateformate setDateFormat:@"dd-MM-yyyy HH:mm:ss ZZZZ"];
    NSLog(@"%@", [dateformate dateFromString:strDate]);
    [dateformate setDateFormat:@"dd-MM-yyyy HH:mm:ss ZZZZZ"];
    NSLog(@"%@", [dateformate dateFromString:strDate]);

Output

2023-01-16 19:01:22.124912+0530 [11231:315465] (null)
2023-01-16 19:01:22.125229+0530 [11231:315465] (null)
2023-01-16 19:01:22.125492+0530 [11231:315465] (null)
2023-01-16 19:01:22.125724+0530 [11231:315465] (null)
2023-01-16 19:01:22.126006+0530 [11231:315465] (null)

Actually I am getting date fro server and what to prepare my NSDate. So in my application as per need I can show different date.

Note: When testing with ZZZZZ on https://nsdateformatter.com it will give proper answer but when try in Xcode 13.3.1 it gives me null.

1

There are 1 answers

2
vadian On

(NS)DateFormatter doesn't support an one digit hour time zone format.

A possible solution is to insert the leading zero with Regular Expression. The pattern searches for a plus or minus sign followed by a single zero followed by a colon and inserts one zero on success. $1 represents the captured plus or minus sign.

The time zone specifier for +00:00 is xxx

NSString *strDate = @"24-08-2022 06:38:50 +0:00";
NSString *trimmedStrDate = [strDate stringByReplacingOccurrencesOfString:@"([+-])0:"
                                                              withString:@"$100:"
                                                                 options:NSRegularExpressionSearch
                                                                   range:NSMakeRange(0, strDate.length)];

NSDateFormatter *dateformatter = [[NSDateFormatter alloc] init];
dateformatter.timeZone = [NSTimeZone localTimeZone];
dateformatter.locale = [NSLocale localeWithLocaleIdentifier: @"en_US_POSIX"];
dateformatter.dateFormat = @"dd-MM-yyyy HH:mm:ss xxx";
NSLog(@"%@", [dateformatter dateFromString: trimmedStrDate]);

Side note: The convenient dot-notation dateformatter.dateFormat = syntax has been introduced more than 10 years ago.