I have date string: Monday, October 11, 2010. How can I create a NSDate object out of it and then get different components like day, month, date, year from it. Please note that format/locale of this string may change at runtime.
Asked
Active
Viewed 309 times
2 Answers
4
Use an NSDateFormatter to create the NSDate, then you can access its components through NSDate properties (you'll need to adjust the format string below):
NSDateFormatter *df = [[NSDateFormatter alloc] init];
[df setDateFormat:@"EEE, dd MMM yyyy HH:mm:ss ZZZ"];
if(NSDate *myDate = [df dateFromString:string]) {
//Do something with myDate
}

Ben
- 2,982
- 1
- 16
- 12
-
I am trying fetching month like theDate.month but it is giving me compilation error. – Abhinav Oct 12 '10 at 00:39
-
1You can use another NSDateFormatter with a custom date style to convert the date back to an NSString for example. You could convert it just to the month number if you want to isolate that. Check the NSDateFormatter reference. – Ben Oct 12 '10 at 00:44
1
another possibility:
NSCalendar *calendar = [NSCalendar currentCalendar];
NSInteger units = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit;
NSDateComponents *components = [calendar components:units fromDate:date];
NSInteger year = [components year];
...

Matthias Bauch
- 89,811
- 20
- 225
- 247