【发布时间】:2012-08-02 08:30:19
【问题描述】:
我需要将 NSString 像这样:“2012-08-01T12:43:35+02:00”转换为 NSDate,但我找不到好的格式...
我使用这个类别代码将 NSString 转换为 NSDate:
[NSDate dateFromString:@"2012-08-01T12:43:35+02:00" withFormat:@"yyyy-MM-dd'T'HH:mm:ssZZZZ"];
+ (NSDate*) dateFromString:(NSString*)dateString withFormat:(NSString*)format
{
return [self dateFromString:dateString withFormat:format andLocaleIdentifier:@"fr"];
}
+ (NSDate*) dateFromString:(NSString*)dateString withFormat:(NSString*)format andLocaleIdentifier:(NSString*)localeIdentifier
{
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:format];
[dateFormatter setTimeZone:[NSTimeZone localTimeZone]];
NSLocale *locale = [[NSLocale alloc] initWithLocaleIdentifier:localeIdentifier];
[dateFormatter setLocale:locale];
[locale release];
NSDate *returnDate = [dateFormatter dateFromString:dateString];
[dateFormatter release];
return returnDate;
}
我尝试了所有格式,但没有一个是正确的......
yyyy-MM-dd'T'HH:mm:ss >> 2012-08-04T18:05:14
yyyy-MM-dd'T'HH: mm:ssv >> 2012-08-04T18:05:14法国时间
yyyy-MM-dd'T'HH:mm:ssvv >> 2012-08-04T18: 05:14GMT+02:00
yyyy-MM-dd'T'HH:mm:ssvvv >> 2012-08-04T18:05:14GMT+02:00
yyyy-MM-dd'T'HH:mm:ssV >> 2012-08-04T18:05:14CEST
yyyy-MM-dd'T'HH:mm:ssVV强> >> 2012-08-04T18:05:14GMT+02:00
yyyy-MM-dd'T'HH:mm:ssVVV >> 2012-08-04T18:05: 14GMT+02:00
yyyy-MM-dd'T'HH:mm:ssVVVV >> 2012-08-04T18:05:14法国时间
yyyy-MM- dd'T'HH:mm:ssz >> 2012-08-04T18:05:14GMT+02:00
yyyy-MM-dd'T'HH:mm:sszz >> 2012-08-04T18:05:14GMT+02:00
yyyy-MM-dd'T'HH:mm:sszzz >> 2012-08-04T18:05:14GMT +02:00
yyyy-MM-dd'T'HH:mm:sszzzz >> 2012-08-04T18:05:14中欧夏令时
yyyy-MM -dd'T'HH:mm:ssZ >> 2012-08-04T18:05:14+0200
yyyy-MM-dd'T'HH:mm: ssZZZ >> 2012-08-04T18:05:14+0200
yyyy-MM-dd'T'HH:mm:ssZZZZ >> 2012-08-04T18:05 :14GMT+02:00
我该怎么办?
[编辑] 第一个丑陋的解决方案:
- 用正则表达式删除最后一个冒号
- 用这种格式“yyyy-MM-dd'T'HH:mm:ssZZZ”转换字符串
有正则表达式
NSString* dateString = @"2012-08-01T12:43:35+02:00";
NSMutableString* dateWithoutColonString = [dateString mutableCopy];
NSRegularExpression* lastColonRegex = [NSRegularExpression
regularExpressionWithPattern:@"([\\+\\-][0-9][0-9]):"
options:NSRegularExpressionCaseInsensitive
error:nil];
[lastColonRegex replaceMatchesInString:dateWithoutColonString
options:NSRegularExpressionCaseInsensitive
range:NSMakeRange(0, [dateString length])
withTemplate:@"$1"];
【问题讨论】:
-
如果您找到任何解决问题的方法,请告诉我
标签: objective-c ios date