iOS RFC3339时间解析为时间戳 记录下

+ (long long)userVisibleDateTimeStringForRFC3339DateTimeString:(NSString *)rfc3339DateTimeString {
    /*
      Returns a user-visible date time string that corresponds to the specified
      RFC 3339 date time string. Note that this does not handle all possible
      RFC 3339 date time strings, just one of the most common styles.
     */

    // If the date formatters aren't already set up, create them and cache them for reuse.
    NSDateFormatter *sRFC3339DateFormatter = nil;
    if (sRFC3339DateFormatter == nil) {
        sRFC3339DateFormatter = [[NSDateFormatter alloc] init];
        NSLocale *enUSPOSIXLocale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"];
        [sRFC3339DateFormatter setLocale:enUSPOSIXLocale];
        if (rfc3339DateTimeString.length == 20) {
            //example 2019-12-14T06:37:56Z
            [sRFC3339DateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss'Z'"];
        }else if (rfc3339DateTimeString.length == 22) {
            [sRFC3339DateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss.S'Z'"];
        }else if (rfc3339DateTimeString.length == 23) {
            //example 2019-12-14T07:36:46.61Z yyyy-MM-dd'T'HH:mm:ss.SS'Z'
            [sRFC3339DateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss.SS'Z'"];
        }else {
            //example 2019-12-14T06:36:42.184Z
            [sRFC3339DateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:sss.SSS'Z'"];
        }
        [sRFC3339DateFormatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];
    }

    // Convert the RFC 3339 date time string to an NSDate.
    NSDate *date = [sRFC3339DateFormatter dateFromString:rfc3339DateTimeString];
    NSString *userVisibleDateTimeString;
    
    if (date != nil) {
        long long timeSp = [date timeIntervalSince1970]*1000;
        userVisibleDateTimeString = [EVUtils getDateDisplayString:timeSp];
        return timeSp;
    }else {
        userVisibleDateTimeString = @"";
        return 0;
    }
}

猜你喜欢

转载自blog.csdn.net/quanhaoH/article/details/128674892