Wrong Date from string returns from formatter! Why?
I have problem with NSDateFormatter I converting date from picker in one view
`NSDateFormatter *output = [[NSDateFormatter alloc] init];
[output setDateStyle:NSDateFormatterMediumStyle];
[output setDateStyle:NSDateFormatterShortStyle];
[output setDateFormat:@"yyyy-MM-dd hh:mm:ss"];
NSString *StringToSend = [output stringFromDate:datePicker.d开发者_StackOverflowate];
` then send string to other nib
where converting it back with that code
`NSDateFormatter *inputFormatter = [[NSDateFormatter alloc] init];
[inputFormatter setDateStyle:NSDateFormatterMediumStyle];
[inputFormatter setDateStyle:NSDateFormatterShortStyle];
[inputFormatter setDateFormat:@"yyyy-MM-dd hh:mm:ss"];
NSDate *formatterDate = [inputFormatter dateFromString:StringFromOtherView];
NSLog(@"%@", formatterDate);`
and it's return wrong date sending 2011-09-26 01:02:49 geting 2011-09-25 22:02:49 +0000
what is wrong?
Because:
- When you
NSLog()
anNSDate
, it always logs it in GMT - You live in a timezone that's three hours ahead of of GMT. Thus, 1:02 am for you is 22:02 pm (of the previous day) in GMT.
Include the timezone on your date format string.
+ (NSDate*) dateFromString:(NSString*)aStr
{
if (aStr.length == 10) {
aStr = [aStr stringByAppendingFormat:@" 00:00:00"];
}
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"MM-dd-yyyy HH:mm:ss"];
dateFormatter.timeZone = [NSTimeZone timeZoneWithAbbreviation:@"GMT"];
NSLog(@"strdate %@", aStr);
NSDate *aDate = [dateFormatter dateFromString:aStr];
NSLog(@"date = %@",aDate);
[dateFormatter release];
return aDate;
}
精彩评论