1

I am using below code, but it gives me one day ahead date .

Example: passing input string as "2013-08-31T23:59:59-0400" and out put date is coming as "2013-09-01 03:59:59 +0000".

NSDateFormatter *formatter = [self railsDateFormatter];
NSDate *date = [formatter dateFromString:dateString];

+(NSDateFormatter*)railsDateFormatter
{
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"YYYY-MM-dd'T'HH:mm:ssZ"];
    NSLocale *locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"];
    [formatter setLocale:locale];
    return formatter;
}

Thank you .

Kumar KL
  • 15,315
  • 9
  • 38
  • 60
hkm
  • 151
  • 1
  • 7
  • You don't seem to be 1 day ahead, more like 4 hours ahead. How is the date formatted when you output it? – David Rönnqvist Jan 30 '14 at 11:59
  • The clue was the timezone offset at the end of the string, first has `-0400` (4 hours behind) and the second has `+0000` (0 hours behind). You have set the local to `en_US_POSIX` and this changed your timezone. No issue here at all – Simon McLoughlin Jan 30 '14 at 13:07
  • If you don't know the difference between YYYY and yyyy, you should use yyyy. But that would only break dates near January 1st. – Greg Parker Jan 30 '14 at 19:51

3 Answers3

6

hi these is happen because of the time zone difference please set time zone proper

-(NSDate *)convertDateFromString:(NSString *)strDate DateFormat:(NSString *)strDateFromat
{
    strDateFromat=@"yyyy-MM-dd'T'HH:mm:ss";

    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    //chirag::In date day is displayed one less so it can print exact date
    formatter.timeZone = [NSTimeZone timeZoneWithAbbreviation: @"GMT"];
    [formatter setDateFormat:strDateFromat];

    NSDate *currentYearDate = [formatter dateFromString:strDate];

    return currentYearDate;
}
David Rönnqvist
  • 56,267
  • 18
  • 167
  • 205
Chirag Shah
  • 3,034
  • 1
  • 30
  • 61
3

Thats probably related to TimeZone issues - is the date your getting in UTC or your local time? Set the timezone of the dateFormatter accordingly

rist
  • 578
  • 2
  • 9
  • This not correct. The input string contains an *explicit time zone* "-0400" that corresponds to the "Z" format, therefore `setTimeZone:` has no effect on the string to date conversion. – Martin R Jan 30 '14 at 12:14
  • ah - ok the parsing would be correct without passing the timezone, but he seems to output the date again in the original timezone - therefore he has to set the timezone for outputtin – rist Jan 30 '14 at 12:58
3

Its a timezone issue. Set the TimeZone of your DateFormatter Object.

[dateFormatter setTimeZone: [NSTimeZone timeZoneWithAbbreviation: @"GMT"]];
Sahil Mahajan
  • 3,922
  • 2
  • 29
  • 43
  • This not correct. The input string contains an *explicit time zone* "-0400" that corresponds to the "Z" format, therefore `setTimeZone:` has no effect on the string to date conversion. – Martin R Jan 30 '14 at 12:14