How to convert a date string like “2011-06-25T11:0

2019-08-29 02:38发布

I need to convert this string date "2011-06-25T11:00:26+01:00” into a long like value.

I tried this

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];

but this doesn't work. Please help me.

Thanks in advance.

2条回答
放荡不羁爱自由
2楼-- · 2019-08-29 03:02

If you want to convert "2011-06-25T11:00:26+01:00” to "2011-06-25T11:00:26GMT+01:00" which can be parsed

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);

Hope this helps you

查看更多
该账号已被封号
3楼-- · 2019-08-29 03:05

First of all, I missed this the first time but "2011-06-25T11:00:26+01:00” is cannot be parsed. The correct string would be "2011-06-25T11:00:26+0100”.

Once you've the string in that format, use the date format – "yyyy-MM-dd'T'HH:mm:ssZ".

Example usage

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);
查看更多
登录 后发表回答