0

我正在尝试获取当月的开始和结束日期。这里有一些类似的问题,但我在使用它们时得到了意想不到的结果。这是我所做的:

NSDate *monthStart,*monthEnd;   
NSCalendar *cal = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];          
NSDateComponents *comps = [cal components:NSDayCalendarUnit fromDate:[NSDate date]];
[comps setDay:1];
[comps setHour:0];
[comps setMinute:0];
[comps setSecond:0];
monthStart = [cal dateFromComponents:comps];
[comps setDay:[[NSCalendar currentCalendar]
               rangeOfUnit:NSDayCalendarUnit
               inUnit:NSMonthCalendarUnit
               forDate:[NSDate date]].length];
[comps setHour:23];
[comps setMinute:59];
[comps setSecond:59];
monthEnd = [cal dateFromComponents:comps];
NSLog(@"%@",monthStart);
NSLog(@"%@",monthEnd);

不幸的是,输出是:

2012-12-24 15:39:28.159 Popup[1010:403] 0001-12-31 18:06:32 +0000
2012-12-24 15:39:28.160 Popup[1010:403] 0001-01-31 18:06:31 +0000

顺便说一句,我机器中配置的时区是 +5:30

4

2 回答 2

1

我对你的代码做了一点修改,以获得正确的答案

NSDate *monthStart,*monthEnd;
NSCalendar *cal = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDate *currentDate = [NSDate date];
NSDateComponents *comps = [cal components:(NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit) fromDate:currentDate];
[comps setDay:1];
[comps setHour:0];
[comps setMinute:0];
[comps setSecond:0];
[cal setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:19800]];
monthStart = [cal dateFromComponents:comps];


[comps setDay:[[NSCalendar currentCalendar] rangeOfUnit:NSDayCalendarUnit inUnit:NSMonthCalendarUnit forDate:[NSDate date]].length];
[comps setHour:23];
[comps setMinute:59];
[comps setSecond:59];
monthEnd = [cal dateFromComponents:comps];

NSLog(@"Start %@",monthStart);
NSLog(@"End   %@",monthEnd);
于 2012-12-24T11:25:58.957 回答
0

如果您想知道当月的开始和结束日期...

开始总是第一天,结束可以按月名计算!!!

然后是非常简单的日期算术,

NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];

NSMutableArray *months=[NSMutableArray arrayWithObjects:@"Jan",@"Feb",@"Mar",@"Apr",@"May",@"Jun",@"Jul",@"Aug",@"Sep",@"Oct",@"Nov",@"Dec", nil];
NSMutableArray *days=[NSMutableArray arrayWithObjects:@"31",@"28",@"31",@"30",@"31",@"30",@"31",@"31",@"30",@"31",@"30",@"31", nil];
//check if leap
[dateFormat setDateFormat:@"YYYY"];
NSInteger year=[[dateFormat stringFromDate:[NSDate date]]integerValue];
if(((year%4==0)&&(year%100!=0))||(year%400==0)) {
    [days replaceObjectAtIndex:1 withObject:@"29"];
}

NSMutableDictionary *daysInMonthDict=[[NSMutableDictionary alloc]initWithObjects:days forKeys:months];

[dateFormat setDateFormat:@"MMM"];
NSLog(@"Starting date is 1 and ending date is %@",[daysInMonthDict objectForKey:[dateFormat stringFromDate:[NSDate date]]]);
于 2012-12-24T11:54:57.597 回答