如何在iOS中获取本月的第一个日期?

时间:2015-06-08 08:15:03

标签: ios objective-c nsdate

我尝试从[NSDate new]获取当月的第一个日期。我的问题是,我总是收到 2015/05/31 ,而不是 2015/05/31 。我甚至尝试将字符串 20150601 转换为NSDate,我仍然收到 2015/05/31

这是我的CODE(第二个元素):

    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
    [dateFormatter setDateFormat:@"yyyyMMdd"];
    [dateFormatter setTimeZone:[NSTimeZone localTimeZone]];
    currentMonth = [dateFormatter dateFromString:@"20150601"];

结果是:

(lldb) print currentMonth
(__NSDate *) $0 = 0x79e64820 2015-05-31 21:00:00 UTC

修改

好的,我理解我的错误 - 我没有正确检查我的操作结果。它们总是导致UTC。 10x,答案和所有评论。下次我会更加小心。

2 个答案:

答案 0 :(得分:2)

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

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

NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
NSTimeZone *zone = [NSTimeZone localTimeZone];
[formatter setTimeZone:zone];
[formatter setDateFormat:@"yyyyMMdd"];


NSDate *dayOneInCurrentMonth = [gregorian dateFromComponents:components];
NSString *currentMonth = [formatter stringFromDate:dayOneInCurrentMonth];
NSLog(@"%@",currentMonth);

输出

2015-06-08 14:07:30.924 NSDATEDemo[1943:39838] 20150601

答案 1 :(得分:0)

NSDateComponents创建[NSDate date],将当前日期设置为1并重新创建NSDate对象:

- (NSDate *) dateAtStartOfMonth
{
    //Not tested!!!
    NSDateComponents *comp = [[NSCalendar currentCalendar] components:(NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit) fromDate:[NSDate date]];
    [comp setDay:1];
    return [[NSCalendar currentCalendar] dateFromComponents:comp];
}