Convert ISO 8601 to NSDate

前端 未结 4 415
星月不相逢
星月不相逢 2020-12-03 01:02

I have a timestamp coming from server that looks like this:

2013-04-18T08:49:58.157+0000

I\'ve tried removing the colons, I\'ve tried all

相关标签:
4条回答
  • 2020-12-03 01:33

    I also have the native API, which is way cleaner... This is the implementation I got in my DateTimeManager class:

    + (NSDate *)getDateFromISO8601:(NSString *)strDate{
    
        NSISO8601DateFormatter *formatter = [[NSISO8601DateFormatter alloc] init];
        NSDate *date = [formatter dateFromString: strDate];
        return date;
    }
    

    Just copy and paste the method, it would do the trick. Enjoy it!

    0 讨论(0)
  • 2020-12-03 01:37

    This works for me:

    NSString *dateString = @"2013-04-18T08:49:58.157+0000";
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss.SSSZ"];
    // Always use this locale when parsing fixed format date strings
    NSLocale *posix = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"];
    [formatter setLocale:posix];
    NSDate *date = [formatter dateFromString:dateString];
    NSLog(@"date = %@", date);
    
    0 讨论(0)
  • 2020-12-03 01:37

    There is New API from Apple! NSISO8601DateFormatter

    NSString *dateSTR = @"2005-06-27T21:00:00Z";
    NSISO8601DateFormatter *formatter = [[NSISO8601DateFormatter alloc] init];
    NSDate *date = [formatter dateFromString:dateSTR];
    NSLog(@"%@", date);
    
    0 讨论(0)
  • 2020-12-03 01:55

    The perfect and best solution that worked for me is:

    let isoFormatter = ISO8601DateFormatter();
    isoFormatter.formatOptions = [ISO8601DateFormatter.Options.withColonSeparatorInTime,
                                          ISO8601DateFormatter.Options.withFractionalSeconds,
                                          ISO8601DateFormatter.Options.withFullDate,
                                          ISO8601DateFormatter.Options.withFullTime,
                                          ISO8601DateFormatter.Options.withTimeZone]
    let date = isoFormatter.date(from: dateStr);
    

    For further more detail, you can refer to apple's official documentation: https://developer.apple.com/documentation/foundation/nsiso8601dateformatter

    0 讨论(0)
提交回复
热议问题