如何将像“2011-06-25T11:00:26 + 01:00”这样的日期字符串转换为像iPhone一样长的字符串?

时间:2011-06-28 06:08:47

标签: iphone objective-c nsdate nsdateformatter

我需要将此字符串日期“2011-06-25T11:00:26 + 01:00”转换为长期值。

我试过这个

NSDateFormatter *df = [[[NSDateFormatter alloc] init] autorelease];

[df setTimeZone:[NSTimeZone timeZoneWithName:@"UTC"]];

[df setDateFormat:@"yyyy-MM-ddHH:mm:ssZ"];

NSDate *date = [df dateFromString:[time stringByReplacingOccurrencesOfString:@"T" withString:@""]];

[df setDateFormat:@"eee MMM dd, yyyy hh:mm"];

NSLog(@"time%@", time);
long lgTime =  (long)[date timeIntervalSince1970];

但这不起作用。请帮帮我。

提前致谢。

2 个答案:

答案 0 :(得分:9)

首先,我第一次错过了这个,但"2011-06-25T11:00:26+01:00”无法解析。正确的字符串为"2011-06-25T11:00:26+0100”

使用该格式的字符串后,请使用日期格式 - "yyyy-MM-dd'T'HH:mm:ssZ"

使用示例

NSString * time = @"2011-06-25T11:00:26+0100";

NSDateFormatter *df = [[[NSDateFormatter alloc] init] autorelease];  
[df setDateFormat:@"yyyy-MM-dd'T'HH:mm:ssZ"];

NSDate *date = [df dateFromString:time];

long lgTime = (long)[date timeIntervalSince1970];

NSLog(@"%ld", lgTime);

答案 1 :(得分:1)

如果您想将“ 2011-06-25T11:00:26 + 01:00 ”转换为“ 2011-06-25T11:00:26GMT + 01:00 “可以解析

NSMutableString *string=[[NSMutableString alloc]initWithString:@"2011-06-25T11:00:26+01:00"];

NSRange range = [string rangeOfString:@"+" options:NSBackwardsSearch];
[string insertString:@"GMT" atIndex:range.location];
NSLog(@"string is %@",string);

希望这有助于你

相关问题