iOS get weekly Monday start and end of Sunday date

Source: Internet
Author: User

Get the time of week Monday Zero (the start of the week) and Sunday 24 o'clock (that is, the end of this week and the start of the next week)

NSDate *now =[NSDate Date]; Nscalendar*calendar =[Nscalendar Currentcalendar]; Nsdatecomponents*comp = [Calendar components:nsyearcalendarunit| Nsmonthcalendarunit| Nsdaycalendarunit| Nsweekdaycalendarunit|Nsdaycalendarunit Fromdate:now]; //get a day of the week//1 (Sunday) 2 (Tuesday) 3 (Wednesday) 4 (Thursday) 5 (Fri) 6 (Saturday) 7 (Sunday)Nsinteger WeekDay =[Comp weekday];//get What?Nsinteger Day =[Comp Day]; NSLog (@"weekday:%ld day:%ld", Weekday,day); //calculates the current date and the number of days between Monday and Sunday of the WeekLongFirstdiff,lastdiff;if(WeekDay = =1) {Firstdiff=1; Lastdiff=0;}Else{Firstdiff= [Calendar Firstweekday]-WeekDay; Lastdiff=9-WeekDay;} NSLog (@"firstdiff:%ld lastdiff:%ld", Firstdiff,lastdiff); //The number of days to add the difference on the current date (minus cent seconds)nsdatecomponents *firstdaycomp = [Calendar components:nsyearcalendarunit| Nsmonthcalendarunit|Nsdaycalendarunit Fromdate:now]; [Firstdaycomp setday:day+Firstdiff]; NSDate*firstdayofweek=[Calendar Datefromcomponents:firstdaycomp]; Nsdatecomponents*lastdaycomp = [Calendar components:nsyearcalendarunit| Nsmonthcalendarunit|Nsdaycalendarunit Fromdate:now]; [Lastdaycomp setday:day+Lastdiff]; NSDate*lastdayofweek=[Calendar Datefromcomponents:lastdaycomp]; NSDateFormatter*formater =[[NSDateFormatter alloc] init]; [Formater Setdateformat:@"YYYY-MM-DD HH:mm:ss"]; NSLog (@"Monday begins%@", [Formater Stringfromdate:firstdayofweek]); NSLog (@"Current%@", [Formater Stringfromdate:now]); NSLog (@"Sunday End%@", [Formater Stringfromdate:lastdayofweek]);

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.