开发者

Wrong Date from string returns from formatter! Why?

开发者 https://www.devze.com 2023-04-07 17:50 出处:网络
I have problem with NSDateFormatter I converting date from picker in one view `NSDateFormatter *output = [[NSDateFormatter alloc] init];

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:

  1. When you NSLog() an NSDate, it always logs it in GMT
  2. 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;

}

0

精彩评论

暂无评论...
验证码 换一张
取 消