简体   繁体   English

如何在iOS中获得上个月的第一天

[英]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将自动减少年份并将月份设置为12月。

 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!!!! 编码愉快!!!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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