nightfixed
nightfixed

Reputation: 841

NSDateFormatter dateFromString wrong result?

I'm trying to get an NSDate object from an NSString. The problem is that, I'm losing 1 day in the process.

This is the NSString: 2015-08-01, and here is the code:

    NSDateFormatter *df = [[NSDateFormatter alloc] init];
    [df setDateFormat:@"yyyy-MM-dd"];
    NSDate *result = [df dateFromString:dateString];

The result turns out to be 2015-07-31 21:00:00 +0000.

How so? I don't understand. Besides, where did the 21:00:00 come from? I'm getting this same result regardless of running the code on a real device or simulator.

Any idea why ? I'm suspecting a timezone issue. However, I'm getting the dateString in UTC format, and I'm not altering it. Thoughts?

Upvotes: 0

Views: 64

Answers (2)

Pallavi Konda
Pallavi Konda

Reputation: 1670

Check with time zone.

[dateFormatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"UTC"]];

Upvotes: 2

Adnan Aftab
Adnan Aftab

Reputation: 14477

Setting time zone will do the trick

NSString *dateString = @"2015-08-01";
    NSDateFormatter *df = [[NSDateFormatter alloc] init];
    [df setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"UTC"]];
    [df setDateFormat:@"yyyy-MM-dd"];
    NSDate *result = [df dateFromString:dateString];

Upvotes: 1

Related Questions