计算实际日期的午夜日期

时间:2013-01-23 17:12:50

标签: objective-c nsdate nsdateformatter date-formatting

  

可能重复:
  Getting date from [NSDate date] off by a few hours

我想用实际日期计算实际当天的午夜时间,这里是代码:

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);

但我得到的日志是:

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

为什么midNight不是实际的午夜,为什么它与formatter的格式不同?

1 个答案:

答案 0 :(得分:0)

这会计算当地时区的午夜时间。

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);

打印23/01/2013 12:00 AM