Reply to a Q &:
Get the start and end time of the previous month for a given date. For example, if the time is, how can we find and?
// The date obtained in this article is the current date of the system. You must specify the date and assign the value to year month day.
Nsinteger year, month, day; nscalendar * Calendar = [[nscalendar alloc] initwithcalendaridentifier: nsgregoriancalendar]; nsdate * Now = [nsdate date]; nsdatecomponents * comps = [[nsdatecomponents alloc] init]; nsinteger unitflags = nsyearcalendarunit | calendar | nsdaycalendarunit | calendar | nshourcalendarunit | calendar | nssecondcalendarunit; comps = [calendar C Omponents: unitflags fromdate: Now]; year = [comps year]; month = [comps month]; Day = [comps Day]; nslog (@ "Now yes: % d Year % d month % dday ", year, month, day); // month obtains the current month, and then determines whether the last month is July if (month! = 1) {// If mouth! = 1, then the first month of the previous month is 1, and the year remains unchanged nslog (@ "last month: % d Month 1", year, month-1 ); // process special cases where last month is July 15, February. If (month! = 3) {// If the month of the previous month is November January, their last month is 30 if (month = 5 | month = 7 | month = 10 | month = 12) {nslog (@ "last month: % d-30 ", year, month-1);} else {nslog (@" last month: % d-31 ", year, month-1) ;}/// if this month is July, the last month is July, and the last month is July 29, non-leap year 28 days else {If (Year % 4 = 0 & year % 100! = 0) | year % 400 = 0) {nslog (@ "last month end: % d month 29", year, month-1 );} else {nslog (@ "last month end: % d month 28", year, month-1) ;}}// if the current month is January, last month is December year-1, month = 12 else {nslog (@ "the beginning of last month is % d Year December 1", year-1 ); nslog (@ "last month's last month is % d Year December 31", year-1 );}
Test results: