views:

40

answers:

2

Hi,

I am developing an application in that i have used DatePicker to pick the date but it gives me date with time .I have converted that format into string, now i just want date from that. How should i do that.Plz suggest me something.

Following is my code Snippet.

  NSDate *selected =[datePicker date];
  NSString *dateString = [NSString stringWithFormat:@"%@", selected];

here date picker is object of UIDatePicker.

A: 

You can use NSCalendar to get the month, day, and year components of your date, manipulate them, and reassemble them. Here's some example code.

NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *dateComponents = [calendar components:( NSYearCalendarUnit | NSMonthCalendarUnit |  NSDayCalendarUnit ) fromDate:date];

[otherDateComponents setYear:[dateComponents year]];
[otherDateComponents setMonth:[dateComponents month]];
[otherDateComponents setDay:[dateComponents day]];

NSDate *newDate = [calendar dateFromComponents:otherDateComponents];

Be aware that since the current calendar is locale-specific, the values you get back will not be the same on all devices. You may wish to specify a particular calendar for your purposes. NSGregorianCalendar is the one most often used in the west.

warrenm
A: 

Here is another solution:

NSDate *selected =[datePicker date];
NSDateFormatter *formatter = [NSDateFormatter new];

[formatter setDateStyle:NSDateFormatterMediumStyle];
NSDate *day = [formatter dateFromString:[formatter stringFromDate:selected]];
[formatter release];
nasim
`NSDateFormatterMediumStyle` is locale-specific. Although unlikely, it is possible that it will not return the fields you want. As long as you can assume the Gregorian calendar, you're safer using an explicit method such as the accepted solution or a custom format string.
warrenm