Manage date with NSDateFormatter
I try to get and manage date with NSDateFormatter but how to make it works. I think it's a problem with my first "dateFormatter" which have not the right format, because when I use the second formatter with function "stringFromDate" and paramter "[NSDate date]" it works well, but not when I use my NSDate "dateFromString".
//"dateString" have this format: "2011-05-26T16:18:26Z"
NSString *dateString = [[tracks objectAtIndex:0] objectForKey:@"to-date"];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"EEE, MMM d, yyyy"];
NSDate *dateFromString = [[NSDate alloc] init];
dateFromString = [dateFormatter dateFromString:dateString];
[dateFormatter release];
dateFormatter = [[NSD开发者_开发技巧ateFormatter alloc] init];
[dateFormatter setDateFormat:@"EEE, MMM d, yyyy"];
//NSString *toDate = [dateFormatter stringFromDate:dateFromString];
NSString *toDate = [dateFormatter stringFromDate:[NSDate date]];
Thank you for your help :)
Well of course, the DateFormat is not the same as the one you are receiving from the server.
Try this:
dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss Z"];
NSDate *date = [dateFormatter dateFromString:[dateString stringByReplacingOccurrencesOfString:@"Z" withString:@" +0000"]];
Assuming that to-date
is a string and not already an NSDate try this instead:
//"dateString" have this format: "2011-05-26T16:18:26Z"
NSString *dateString = [[tracks objectAtIndex:0] objectForKey:@"to-date"];
NSDate *dateFromString = [[NSDate dateFromString:dateString];
If you want to display a date to the user formatted in a particular format you can then use set up an NSDateFormatter
and use stringFromDate:
to get a string to show the user. If it still doesn't display correctly set the calendar (I forget if you always have to set it or if there is a default).
精彩评论