Search code examples
objective-ciphonensdateformatterios13

How to format date 12/2/31 H, 2:21:41 AM in Objective-c?


This is what date I am getting again our current date of 2019.

12/2/31 H, 2:21:41 AM

Can anyone help me how can I parse this date to NSDate object in Objective-c?


Solution

  • This calendar format belongs to the Japanese Calendar.

    To parse the date with NSDateFormatter you have to replace the H with Heisei and assign a Japanese Calendar instance to the date formatter.

    NSString *dateString = [@"12/2/31 H, 2:21:41 AM" stringByReplacingOccurrencesOfString:@"H" withString:@"Heisei"];
    NSCalendar *japanese = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierJapanese];
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    formatter.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US@calendar=japanese"];
    formatter.calendar = japanese;
    formatter.dateFormat = @"MM/d/yy G, h:mm:ss a";
    NSDate *date = [formatter dateFromString:dateString];
    NSLog(@"%@", date);