Problem with parsing NSString to NSDate
I have XML wit开发者_开发技巧h this value:
<LastModifiedOnDate>2011-04-02T00:00:00</LastModifiedOnDate>
I am trying to parse this on iPhone from NSString to NSDate but have no luck.
NSDateFormatter *formate = [[[NSDateFormatter alloc] init] autorelease];
[formate setDateFormat:@"yyyy'-'MM'-'dd'T'HH':'mm':'ss"];
//NSString *strConcat = @"2010-09-24 17:30:00";
NSDate *date = [formate dateFromString:string];
You don't need all those apostrophes in your format string. The only ones you need are around the T.
NSDateFormatter *formate = [[[NSDateFormatter alloc] init] autorelease];
[formate setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss"];
// I recommend setting a timezone because it will use the system timezone and that
// can cause confusion with your data.
// [formate setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];
NSString *strConcat = @"2010-09-24T17:30:00";
NSDate *date = [formate dateFromString:strConcat];
NSLog(@"Date: %@", date); // remember NSDate default to current timezone when logging to console
If you string have fraction of seconds, then add SSS to your string format: [formate setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss.SSS"];
For additional information on date formatting check out Unicode Technical Standard #35.
Replace your's SetDataFormat
function with below and let me know for the result ...
[formate setDateFormat:@"yyyy-MM-ddTHH:mm:ss"];
NSString *string=@"2011-04-05T12:43:56.537";
NSDateFormatter *formate = [[[NSDateFormatter alloc] init] autorelease];
[formate setDateFormat:@"yyyy'-'MM'-'dd'T'HH':'mm':'ss.SSS"];
NSDate *date = [formate dateFromString:string];
its working..
精彩评论