rawDesign
rawDesign

Reputation: 35

NSString to NSDate conversion using NSDateFormatter > date way off

Trying to convert a datetime from NSString to NSDate using NSDateFormatter. I know it should be a simple task, but it's not - the converted NSDate is whole 20 days off. I cannot find the cause for this. Already tried every solution I could find (different locales, time zones, formattings ...) but no luck so far.

Here's a code sample:

NSString *strDate = @"24.01.2014 08:17:10";
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
NSLocale *locale = [NSLocale currentLocale];
[dateFormat setDateFormat:@"dd.MM.YYYY HH:mm:ss"];
[dateFormat setLocale:locale];
[dateFormat setTimeZone:[NSTimeZone timeZoneWithName:@"CET"]];
NSDate *dte = [dateFormat dateFromString:strDate];

output of dte is "04.01.2014 08:17:10". As you can see, the time is correct, but the date is way off.

Upvotes: 0

Views: 56

Answers (2)

Sujith Thankachan
Sujith Thankachan

Reputation: 3506

Use the following code

NSString *strDate = @"24.01.2014 08:17:10";
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"dd.MM.yyyy HH:mm:ss"];
NSDate *date = [dateFormat dateFromString:strDate];

Upvotes: 0

rckoenes
rckoenes

Reputation: 69479

There is an error in your time format, YYYY should be yyyy.

NSString *strDate = @"24.01.2014 08:17:10";
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
NSLocale *locale = [NSLocale currentLocale];
[dateFormat setDateFormat:@"dd.MM.yyyy HH:mm:ss"];
[dateFormat setLocale:locale];
[dateFormat setTimeZone:[NSTimeZone timeZoneWithName:@"CET"]];
NSDate *dte = [dateFormat dateFromString:strDate];

Will give me as output : 2014-01-24 07:17:10 +0000

Upvotes: 1

Related Questions