我想用实际日期计算实际当天的午夜时间,这里是代码:
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
的格式不同?
答案 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