简体   繁体   中英

How to get last month's First day in iOS

我正在开发一个日历应用程序,当我导航到下个月时,它可以正常工作,因为我可以到达该月的最后一天,从那里我可以到达下个月的第一天。但是当我导航到上一个月month im无法获取上个月的第一天。有什么方法可以获取上个月的第一天。

The following works fine for me

NSCalendar *calendar = [NSCalendar currentCalendar];
NSDate *currentDate = [NSDate date];

NSDateComponents *components = [calendar components:(NSCalendarUnitDay | NSCalendarUnitMonth | NSCalendarUnitDay) fromDate:currentDate];

components.month = components.month - 1;
components.day = 1;

NSDate *newDate = [calendar dateFromComponents:components];

This also works if your current month is january. NSDateComponents will automatically decrement the year and set the month to december.

 NSDateComponents *components = [[NSCalendar currentCalendar] components:NSCalendarUnitDay | NSCalendarUnitMonth | NSCalendarUnitYear
                                                                   fromDate:[NSDate date]];
    components.day = 1;
    components.month = components.month - 1;

    NSDate *lastmonthDay1 = [[NSCalendar currentCalendar] dateFromComponents: components];


    NSLog(@"First day of last month====: %@", [lastmonthDay1 descriptionWithLocale:[NSLocale currentLocale]]);

You can do something like below....

     NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
[gregorian setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"UTC"]];
NSDateComponents *comp = [gregorian components:(NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit) fromDate:[NSDate date]];
[comp setDay:1];
[comp setMonth:CurrentMonth];//previous month
[comp setYear:currentYear];
NSDate *firstDayOfMonthDate = [gregorian dateFromComponents:comp];
NSCalendar *cal1=[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *comps1 = [cal1 components:NSWeekdayCalendarUnit fromDate:firstDayOfMonthDate];
// 1 for mon 8 for sun
int startWithDay=[comps1 weekday]==1?8:[comps1 weekday];
//1 for monday 
// 2 for tuesday and so on....

Let me know it is working or not!!!

Happy Coding!!!!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM