1

Possible Duplicate:
UIDatePicker and NSDate

Can I do this and how? I simply need to get the day inputted by the user and put it into a label, rather than the whole date (e.g. old: 28/10/2011 new: 28)

Thanks

Community
  • 1
  • 1
pixelbitlabs
  • 1,934
  • 6
  • 36
  • 65
  • Did you take a look at `NSDateFormatter?` http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSDateFormatter_Class/Reference/Reference.html – Faser Oct 10 '11 at 19:35
  • I did, and managed to put the full date in, but not just the day :'( – pixelbitlabs Oct 10 '11 at 19:37

2 Answers2

3

If your user input is text you will need to start with an NSDateFormatter and then you can extract the day from the calendar components. (I recommend collecting the date through a UIDatePicker)

//Start here for a date that is a string
NSString *userinput = @"28/10/2011";

NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"dd/MM/yyyy"];
NSDate *date = [formatter dateFromString:userinput];
[formatter release];

//Start here if you already have an `NSDate` object
NSDateComponents *components = [[NSCalendar currentCalendar] components:NSDayCalendarUnit 
                                                               fromDate:date];

NSString *dayForLabel = [NSString stringWithFormat:@"%d", [components day]];
Joe
  • 56,979
  • 9
  • 128
  • 135
  • great, thanks! How would I add the event to the iPhones calendar using the full DatePicker date? – pixelbitlabs Oct 10 '11 at 19:51
  • The instructions for that are in the [Event Kit Programming Guide](http://developer.apple.com/library/ios/#documentation/DataManagement/Conceptual/EventKitProgGuide/EditingEventsProgrammatically.html#//apple_ref/doc/uid/TP40005158-SW1) – Joe Oct 10 '11 at 19:53
  • Thanks! Also, I've put this: http://pastie.org/2672944 but the label has a "%" in it rather than the actual day number... Why is this? :) – pixelbitlabs Oct 10 '11 at 19:55
  • You need to format the string with the day, `CalLabel1.text = [NSString stringWithFormat:@"%d", [components day]];` – Joe Oct 10 '11 at 19:58
  • Works now - thanks for your excellent and fast help! :-) – pixelbitlabs Oct 10 '11 at 20:00
  • Would you mind looking at the code I'm using to create an event as it's not working for me? http://stackoverflow.com/questions/7718006/xcode-why-is-my-event-not-being-added-to-the-calendar - thanks! – pixelbitlabs Oct 10 '11 at 20:02
1

Something like this:

NSDate *date = [picker date];

NSCalendar *calendar = [picker calendar];

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

NSInteger day = [dateComponents day];

label.text = [NSString stringWithFormat:@"%d", day];
jbat100
  • 16,757
  • 4
  • 45
  • 70