将“2011-11-04T18:30:49Z”转换为“MM / dd / yy hh:mm:SS a”格式

时间:2011-11-04 19:37:16

标签: ios cocoa nsdate nsdateformatter

我需要从这种格式转换日期:" 2011-11-04T18:30:49Z"

采用以下格式:" MM / dd / yy hh:mm:SS a"

添加用户系统currentGMTOffset偏移量提取:

NSTimeZone* currentTimeZone = [NSTimeZone localTimeZone];  
NSInteger currentGMTOffset = [currentTimeZone secondsFromGMT];

非常感谢任何帮助。

谢谢!

3 个答案:

答案 0 :(得分:1)

此代码段将帮助您将格式化字符串转换为NSDate。

    // Current date.
    NSString *currentDate = @"2011-11-04T18:30:49Z";

    // NSDateFormatter stuff.
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setTimeZone:[NSTimeZone localTimeZone]];
    [dateFormatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"]];
    [dateFormatter setDateFormat:@"yyyy'-'MM'-'dd'T'HH':'mm':'ss'Z'"];

    // Convert to NSDate.
    NSDate *neededDate = [dateFormatter dateFromString:currentDate];

然后您只需要转换为您要求的格式。

我正在使用ARC,因此无需内存管理。

答案 1 :(得分:0)

看看NSDateFormatter。您需要在日期格式化程序对象上设置日期格式和时区,然后您可以将字符串转换为日期和日期为字符串。

答案 2 :(得分:0)

+ (NSString *)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.
 */

NSDateFormatter *rfc3339DateFormatter = [[NSDateFormatter alloc] init];
NSLocale *enUSPOSIXLocale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"];

[rfc3339DateFormatter setLocale:enUSPOSIXLocale];
[rfc3339DateFormatter setDateFormat:@"yyyy'-'MM'-'dd'T'HH':'mm':'ss'Z'"];
[rfc3339DateFormatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];

// Convert the RFC 3339 date time string to an NSDate.
NSDate *date = [rfc3339DateFormatter dateFromString:rfc3339DateTimeString];

NSString *userVisibleDateTimeString;
if (date != nil) {
    // Convert the date object to a user-visible date string.
    NSDateFormatter *userVisibleDateFormatter = [[NSDateFormatter alloc] init];
    assert(userVisibleDateFormatter != nil);

    [userVisibleDateFormatter setDateStyle:NSDateFormatterShortStyle];
    [userVisibleDateFormatter setTimeStyle:NSDateFormatterShortStyle];

    userVisibleDateTimeString = [userVisibleDateFormatter stringFromDate:date];
}
return userVisibleDateTimeString;

}

这可能会有所帮助。