问题
I have the following code:
NSDateFormatter * df = [[NSDateFormatter alloc] init];
[df setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
[df setTimeZone:[NSTimeZone systemTimeZone]];
[df setFormatterBehavior:NSDateFormatterBehaviorDefault];
myres.start_date = [df dateFromString:[NSString stringWithFormat:@"%@ %@", [self.data objectForKey:@"date"], [self.data objectForKey:@"start_time"]]];
NSLog(@"Start date is %@", [NSString stringWithFormat:@"%@ %@", [self.data objectForKey:@"date"], [self.data objectForKey:@"start_time"]]);
NSLog(@"Start date from NSDate is %@", myres.start_date);
myres.end_date = [df dateFromString:[NSString stringWithFormat:@"%@ %@", [self.data objectForKey:@"date"], [self.data objectForKey:@"end_time"]]];
NSLog(@"End date is %@", [NSString stringWithFormat:@"%@ %@", [self.data objectForKey:@"date"], [self.data objectForKey:@"end_time"]]);
NSLog(@"End date from NSDate is %@", myres.end_date);
and the result I am getting is:
Start date is 2011-03-31 9:00:00
Start date from NSDate is 2011-03-31 16:00:00 +0000
End date is 2011-03-31 10:00:00
End date from NSDate is 2011-03-31 17:00:00 +0000
why is the result different? I would like to have it so that when I call myres.start_date description, it gives me the same data as the string.
回答1:
The result is different because you are printing your NSDate
instances using the generic description
method, which doesn't match the output format you expect.
If you used [df stringFromDate:myres.start_date]
you should get the same output.
Keep in mind that NSDate
stores a representation of time, and there are many ways to print time and description
's way of printing time is fixed.
The only way to have description
of NSDate
return a string in the format you want is to override it with a category or use a subclass.
You seem to have a fundamental misunderstanding of how time is stored and displayed: your NSDate
is storing the time parsed by NSDateFormatter
, and it is in fact returning out the same data in its description
method. It is just displaying it in a different form.
回答2:
The date formatter takes the time zone into account. When you use the date directly, you just get it's description, which is apparently zulu time.
来源:https://stackoverflow.com/questions/5509252/nsdate-format-and-value-strange-behavior