获取第一天从NSCalendar一个月(Get first day in a month from

2019-07-20 17:12发布

我有一个需要得到日当月的一个方法的这个子集。

NSDate *today = [NSDate date];  // returns correctly 28 february 2013
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *components = [[NSDateComponents alloc] init];
components.day = 1;
NSDate *dayOneInCurrentMonth = [gregorian dateByAddingComponents:components toDate:today options:0];

dayOneInCurrentMonth然后打印出来2013-03-01 09:53:49 +0000 ,下个月的第一天。

如何获得日当月的一个?

Answer 1:

你的逻辑是错误的:不用日期的日设置为1,您要添加的一天为当前日期。

尝试类似的东西:

NSDate *today = [NSDate date];
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];

NSDateComponents *components = [gregorian components:(NSEraCalendarUnit | NSYearCalendarUnit | NSMonthCalendarUnit) fromDate:today];
components.day = 1;

NSDate *dayOneInCurrentMonth = [gregorian dateFromComponents:components];


Answer 2:

你想[NSCalender dateFromComponents:]而不是:

NSDate *dayOneInCurrentMonth = [gregorian dateFromComponents:components];


Answer 3:

获得从给定日期1日简单的方法:

NSDate *first = [gregorian dateBySettingUnit:NSCalendarUnitDay value:1 ofDate:date options:0]; 


Answer 4:

简单的方法来获得第一和最后一天的前一个月是:

NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
NSDateComponents *comp = [gregorian components:(NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay ) fromDate:[NSDate date]];

//TO GET PREVIOUS MONTH LAST DAY
[comp setMonth:[comp month]];
[comp setDay:1];
NSDate *tDateMonth = [gregorian dateFromComponents:comp];
NSLog(@"LAST DAY OF PREVIOUS MONTH ;  %@", tDateMonth);

//TO GET PREVIOUS MONTH FIRST DAY
[comp setMonth:[comp month]-1];
[comp setDay:3];
NSDate *td = [gregorian dateFromComponents:comp];
NSLog(@"FIRST DAY OF PREVIOUS MONTH ;  %@", td);

希望这可以帮助



Answer 5:

通过创建新的变量是对内存的使用昂贵的,最好使用日期格式,以获得当月的第一天

today = [NSDate date];

firstDayDateFormatter = [[NSDateFormatter alloc] init];
[firstDayDateFormatter setDateFormat:@"01-MM-yyyy"];
dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"dd-MM-yyyy"];
[dateFormatter setLocale:[NSLocale localeWithLocaleIdentifier:@"en_US"]];
firstDayOfTheMonth = [mdfDateFormat dateFromString:[firstDayDateFormatter stringFromDate:today]];


Answer 6:

NSDate *startDate = nil;
[[NSCalendar currentCalendar] rangeOfUnit:NSCalendarUnitMonth startDate:&startDate interval:NULL forDate:date];

return startDate;


文章来源: Get first day in a month from NSCalendar