1

Im using CFAbsoluteTimeGetCurrent() to get the current time, as a CFAbsoluteTime struct.

What is the best way of getting the CFAbsoluteTime of midnight of today?

Ive considered getting midnight using a similar method to the one shown here and then converting the result to a CFAbsoluteTime, but this seems ridiculously complicated to do a simple thing.

Is there a better way?

Community
  • 1
  • 1
Jimmery
  • 9,783
  • 25
  • 83
  • 157

1 Answers1

3

Computing "midnight of the current day" is not completely trivial, because things as the time zone and daylight savings time transitions must be taken into account. My preferred way is

NSCalendar *calendar = [NSCalendar currentCalendar];
NSDate *midnight;
[calendar rangeOfUnit:NSDayCalendarUnit
            startDate:&midnight
             interval:NULL
              forDate:[NSDate date]];

which you can then convert with

CFAbsoluteTime cfMidnight = [midnight timeIntervalSinceReferenceDate];
Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382
  • 1
    For a specific example: Brazil does DST transitions at midnight. This means that, in (parts of) that country, midnight on the third Sunday of October does not exist (since clocks jump forward to, presumably, 01:00, just as we in most of the US skip from 02:00 to 03:00 on our DST start date, so 02:00 doesn't exist). https://en.wikipedia.org/wiki/Daylight_saving_time_in_Brazil (And, just like in the US, whether all of that happens depends on which state you're in.) A more answerable question is β€œat what moment does this day-of-the-calendar start?”, and that's what your code does. – Peter Hosey Aug 22 '13 at 20:40