Obtains the start and end time of the previous month of the specified date.

Source: Internet
Author: User

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:


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.