1

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.date];

` 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?

Cœur
  • 37,241
  • 25
  • 195
  • 267
VSKMEDIA
  • 11
  • 2
  • 2
    Why are you setting MediumStyle and then short style? And then specifying an explicit date format. Looks like output from the Department of Redundancy Department. – Hot Licks Sep 25 '11 at 22:21
  • "Department of Redundancy Department". Hilarious! – Hahnemann May 20 '14 at 08:20

3 Answers3

5

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.
Dave DeLong
  • 242,470
  • 58
  • 448
  • 498
  • +1 for Great Answer..! Day by day I am becoming a fan of yours. I look up to you and if I can be as knowledgable as you one day then I think I will achieve great success :] – Parth Bhatt Sep 26 '11 at 06:28
0
 + (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;

}

Ashish Chauhan
  • 1,316
  • 15
  • 22
0

Include the timezone on your date format string.

Alastair Stuart
  • 4,165
  • 3
  • 36
  • 33
  • But see [here](http://stackoverflow.com/questions/6613110/what-is-the-best-way-to-deal-with-the-nsdateformater-locale-feature). You should set the locale in addition to setting the timezone. – Hot Licks Sep 25 '11 at 22:25