2

Is there any way using NSCalender you can get same day of last month?

I am using a calender which shows user 1 month like the iPad calender when they click on the button I want to move to previous month but should select the same day as before.

I want to just do

[components setMonth:([components month] - 1)];

but this will create problems when I are moving from a month with 31 days to month with 30 days and selected day is 31st.

I was able to find examples for android but not iOS.

android example

Any help would be appreciated

Community
  • 1
  • 1
pa12
  • 1,493
  • 4
  • 19
  • 40
  • This will occur with leap years also.... So what you want one day less or one day more? Facebook shows 28th as birthday for 29th Feb born on non-leap years!!! – Anoop Vaidya Jan 25 '13 at 20:01
  • 1
    what is your requirement if its 31st December on subtracting 1 month what it should be? – Zaheer Ahmed Jan 25 '13 at 20:38

2 Answers2

3

Check out this link.

It's about adding one month, but you could probably do the same with subtracting.

Change

[dateComponents setMonth:1];

into

[dateComponents setMonth:-1];
Community
  • 1
  • 1
Chris Loonam
  • 5,735
  • 6
  • 41
  • 63
  • This might lead to an invalid date. (Dec 31st -> Nov 31st) – Thorsten Jan 25 '13 at 20:57
  • This answer is correct (it won't result in Nov 31st). If you see an incorrect date when you log it, it's probably because `NSDate`'s `description` method formats it as GMT. Make sure that you show both dates with the same time zone. – omz Jan 25 '13 at 21:40
1

Seems there is no obvious "right" answer and no "built-in" answer.

As Chris's "simple" idea may lead to invalid dates, you may have to handle the edge-cases.

Pseudocode to deal with day-month-year:

  1. if month = December start with day-1-(year-1), else day-(month-1)-year [using dateComponents]
  2. check if this a valid date (using NSDateFormatter like in this question
  3. repeat subtracting one day until you reach a valid date

Another idea:

prevMonthDate = startDate;
Repeat
    prevMonthDate = prevMonthDate - 1 day
Until (Month(prevMonthDate) < Month(startDate) Or Year(prevMonthDate) < Year(startDate))
    And (Day(prevMonthDate) <= Day(startDate))

This requires working with NSDate and NSDateComponents, check out the Date and Time Programming Guide.

Community
  • 1
  • 1
Thorsten
  • 12,921
  • 17
  • 60
  • 79