0

Possible Duplicate:
Getting date from [NSDate date] off by a few hours

I want to calculate the actual day's midnight time using the actual day's date here is the code:

NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
    [formatter setDateFormat:@"dd/MM/yyyy"];
 NSDate *today = [NSDate date];
    NSString *todayStr = [NSString stringWithFormat:@"%@ 12:59 PM",[formatter stringFromDate:today]];
NSLog(@"%@",todayStr);
[formatter setDateFormat:@"dd/MM/yyyy hh:mm a"];
NSDate *midNight = [formatter dateFromString:todayStr];
NSLog(@"%@",midNight);

But the log I get is :

23/01/2013 12:59 PM
2013-01-23 10:59:00 +0000

Why does midNight isn't the actual midnight and why does it have a different format from formatter?

Community
  • 1
  • 1

2 Answers2

1

The midnight you calculated with date formatter takes the localization into account.

So, you are living in a UTC+2 timezone.

You can add a 'Z' for UTC.

See more at http://www.w3.org/TR/NOTE-datetime

ZhangChn
  • 3,154
  • 21
  • 41
0

This calculates midnight for your local timezone.

NSDate *d = [NSDate date];
NSCalendar *cal = [NSCalendar currentCalendar];
NSDateComponents *comps = [cal components:NSEraCalendarUnit|NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit fromDate:d];
d = [cal dateFromComponents:comps];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"dd/MM/yyyy hh:mm a"];
NSString *dateStr = [formatter stringFromDate:d];
NSLog(@"%@", dateStr);

prints 23/01/2013 12:00 AM

Bart Whiteley
  • 1,426
  • 12
  • 10