Question

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

Was it helpful?

Solution

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];

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top