10
9

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

NSDateで月末月初 ※ただしGMTに注意

Posted at

今月初から末までのデータを取得するために、月初と月末日を取得するためにこんな感じのコードを書きました。

    NSDate *date = [NSDate date];
    NSLog(@"date = %@",date);
    NSCalendar *calendar = [NSCalendar currentCalendar];
    calendar.locale = [NSLocale currentLocale];
    NSDateComponents *comp =  [calendar components:NSYearCalendarUnit
                               | NSMonthCalendarUnit
                               | NSDayCalendarUnit
                               | NSHourCalendarUnit
                               | NSMinuteCalendarUnit
                               | NSSecondCalendarUnit
                                          fromDate:date];
    comp.day    = 1;
    comp.hour   = 0;
    comp.minute = 0;
    comp.second = 0;
    NSDate *monthBeginningDate =  [calendar dateFromComponents:comp];
    NSLog(@"monthBeginningDate = %@",monthBeginningDate);
    NSLog(@"monthBeginningDate = %@",[monthBeginningDate descriptionWithLocale:[NSLocale currentLocale]]);
    
    NSRange range = [calendar rangeOfUnit:NSDayCalendarUnit inUnit:NSMonthCalendarUnit forDate:date];
    int lastDay =  range.length;
    comp.day = lastDay;
    NSDate *monthEndingDate = [calendar dateFromComponents:comp];
    NSLog(@"monthEndingDate = %@",monthEndingDate);
    NSLog(@"monthEndingDate = %@",[monthEndingDate descriptionWithLocale:[NSLocale currentLocale]]);

注意点としては、NSDateは単純にログ出力すると、グリニッジ標準時で日付が出力されます。
なので、例えば2014年の5月の月初と月末を取得すると、
月初=2014-04-30 15:00:00 +0000
月末=2014-05-30 15:00:00 +0000
となってしまいますが、これはバグっているからではなく、グリニッジ標準時標準時換算であるためです。
(恥ずかしながら、これでちょっと混乱してハマってしまいました)

ロケール付きで出力すると、このように期待した日付が取得できている事が確認できます。
Thursday, May 1, 2014 at 12:00:00 AM Japan Standard Time
Saturday, May 31, 2014 at 12:00:00 AM Japan Standard Time

10
9
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
10
9

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?