8

我有一个方法的这个子集,需要获取当前月份的第一天。

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,下个月的第一天。

如何获得当月的第一天?

4

6 回答 6

17

您的逻辑是错误的:您没有将日期设置为 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];
于 2013-02-28T10:06:00.350 回答
1

从给定日期到第一个的简单方法:

NSDate *first = [gregorian dateBySettingUnit:NSCalendarUnitDay value:1 ofDate:date options:0]; 
于 2015-02-11T22:57:32.467 回答
1

你想要[NSCalender dateFromComponents:]

NSDate *dayOneInCurrentMonth = [gregorian dateFromComponents:components];
于 2013-02-28T10:06:08.260 回答
1

获取上个月的第一个和最后一个日期的简单方法是:

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);

希望这可以帮助

于 2016-01-20T15:33:40.890 回答
0
NSDate *startDate = nil;
[[NSCalendar currentCalendar] rangeOfUnit:NSCalendarUnitMonth startDate:&startDate interval:NULL forDate:date];

return startDate;
于 2017-08-05T10:07:06.493 回答
0

通过创建新变量会消耗内存,最好使用日期格式化程序来获取当月的第一天

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]];
于 2016-03-30T02:46:50.347 回答