问题描述
我有一个方法的这个子集,需要获取当前月份的第一天.
I have this subset of a method that needs to get day one of the current month.
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
,即下个月的第一天.
dayOneInCurrentMonth
then prints out 2013-03-01 09:53:49 +0000
, the first day of the next month.
如何获得当月的第一天?
How do I get day one of the current month?
推荐答案
你的逻辑是错误的:你没有将日期的天数设置为 1,而是在当前日期上添加了一天.
Your logic is wrong: Instead of setting the date's day to 1, you're adding a day to the current date.
试试这样的:
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];