我正在尝试获取当月的开始和结束日期。这里有一些类似的问题,但在使用它们时我得到了意想不到的结果。这就是我的所作所为:
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
BTW,我机器配置的时区是+5:30
答案 0 :(得分: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);
答案 1 :(得分:0)
如果您想知道当月的开始和结束日期......
开始时间始终为1,结束时间可以按月名称计算!!!
然后是非常简单的日期算术,
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]]]);