Search code examples
cocoansdatenscalendarnsdatecomponents

Stripping the time out of an NSDate


I have seen many version of the following code to remove the time element from an NSDate.

NSCalendar *cal = [NSCalendar currentCalendar];
NSDate *now = [NSDate date];
unsigned int intFlags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit;
NSDateComponents *components = [cal components:intFlags fromDate:now];

NSDate *today = [cal dateFromComponents:components];

Trouble is it does not work as expected. I am currently in British summertime (BST). If I run this code now, now=@"2012-07-07 19:24:06 +0000"

today=@"2012-07-06 23:00:00 +0000"

What I want to see is today=@"2012-07-07 00:00:00 +0000"

I can only guess that it has something to do with daylight saving. Any ideas?


Solution

  • You are getting midnight BST (which is GMT+1 hour), which is the same as 23:00 GMT (+0000).

    [NSDate date] will return a date in the current timezone, so your date is in BST. Have you also tried setting the timezone to GMT:

    [components setTimeZone:[NSTimeZone timeZoneWithName:@"GMT"]];