How to convert a date string like “2011-06-25T11:00:26+01:00” to a long like iphone?

僤鯓⒐⒋嵵緔 提交于 2019-12-25 17:04:52

问题


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.


回答1:


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



回答2:


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



来源:https://stackoverflow.com/questions/6502284/how-to-convert-a-date-string-like-2011-06-25t1100260100-to-a-long-like-iph

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!