IOS custom date demo sharing

Time:2021-10-25

There is a project requirement to select a date, which is this:

After reading the demo of several dates on the Internet, it’s too thick and cumbersome to transplant, and then I plan to write it myself.

Let’s write a simplified demo first. There are several key points:

  • First, get the number of days in this month according to the current date
  • Then judge the day of the week on the first day of the month
  • Then display the data in a reasonable position according to the above two data
  • Also record the current date to facilitate month switching
  • If you call the interface, you can display the data according to the data comparison given by the background

One of them is easy to get confused. Sunday is the first day and the subscript is 1

So our array is like this

_ Weekdays = [nsarray arraywithobjects: [nsnull null], @ “Sunday”, @ “Monday”, @ “Tuesday”, @ “Wednesday”, @ “Thursday”, @ “Friday”, @ “Saturday”, nil];
OK, let’s see the effect:

Generally speaking, it’s not difficult. Just get familiar with the API about dates

//3. Get the total number of days in this month and fill in the data source
 NSRange range = [calendar rangeOfUnit:NSCalendarUnitDay inUnit:NSCalendarUnitMonth forDate:self.currentDate];
 NSUInteger numberOfDaysInMonth = range.length;
 NSLog(@"%lu", (unsigned long)numberOfDaysInMonth);
 
 //4. Get the day of the week on the first day of the month
 NSCalendar *cal = [NSCalendar currentCalendar];
 NSDateComponents *comps = [cal
    components:NSCalendarUnitYear | NSCalendarUnitMonth
    fromDate:self.currentDate];
 lastMonthComps.day = 1;
 NSDate *firstDay = [cal dateFromComponents:comps];
 NSCalendarUnit calendarUnit = NSCalendarUnitWeekday;
 NSDateComponents *firsComponents = [cal components:calendarUnit fromDate:firstDay];
 
 NSLog(@"%@", [_weekdays objectAtIndex:firsComponents.weekday]);

Demo complete code

The above is the whole content of this article. I hope it will be helpful to your study, and I hope you can support developpaer.

Recommended Today

SQL statement of three-level linkage of provinces, cities and counties

The first is the table creation statement Copy codeThe code is as follows: CREATE TABLE `t_address_province` ( `id` INT AUTO_ Increment primary key comment ‘primary key’,`Code ` char (6) not null comment ‘province code’,`Name ` varchar (40) not null comment ‘province name’)Engine = InnoDB default charset = utf8 comment = ‘province information table’; CREATE TABLE […]