0

I would like to get the day number from a date. I have the following code which is producing undesirable output:

NSDateFormatter* numDay = [[MSDateFormatter alloc]init];
numDay.dateFormat = @"DD";
dateString = [numDay stringFromDate:the_dte];
DayNum.text = [NSString stringWithFormat:@"%@", dateString];

For instance, if the_dte is 2014-01-07 I get a dayNum of 38

I would like dayNum to hold 7 instead. I assume it has to do with my format. I just do not know a format to put it in to get what I want.

rmaddy
  • 314,917
  • 42
  • 532
  • 579
Burning Hippo
  • 787
  • 1
  • 20
  • 47
  • 1
    Refer to [the documentation](http://www.unicode.org/reports/tr35/tr35-25.html#Date_Format_Patterns). For day of month use "d" or "dd". "DD" will get you day of year (though haven't a clue why it's 38 for the 7th). And there is no formatter code to get day of week -- for that you'd need to use NSCalendarComponents. – Hot Licks Jan 06 '14 at 16:44
  • Bookmark that site -- it will save you hours of flailing around. – Hot Licks Jan 06 '14 at 16:46
  • And Hot Licks beats me once again. Darn you! (Well done.) – Putz1103 Jan 06 '14 at 16:48

1 Answers1

0

In your example the_dte should be an NSDate. If that is the case then I think you should read this answer to get exactly what you are looking for.

Basically you can get the date components from an NSDate by

NSDateComponents *components = [[NSCalendar currentCalendar] components:NSCalendarUnitDay | NSCalendarUnitMonth | NSCalendarUnitYear fromDate:the_dte];
NSInteger day = [components day];
NSInteger month = [components month];
NSInteger year = [components year];

Then format those components into whatever strings you would like using NSString's stringWithFormat: and assign that to your label text

Community
  • 1
  • 1
Putz1103
  • 6,211
  • 1
  • 18
  • 25