NSDateFormatter returns an invalid date from a string

I have a method

+ (NSDate *) convertToDateFrom:(NSString *) dateString { if (dateString == nil || [dateString isEqual:@""]) return nil; //return nil if dateString is empty NSDateFormatter *df = [[NSDateFormatter alloc] init]; [df setDateFormat:@"EEEE, dd MMMM yyyy HH:mm"]; NSDate *date = [df dateFromString:dateString]; return date; } 

When i pass

 @"Monday, 21 November 2011 17:01" //Passed string 

It returns the wrong date,

 2011-11-21 23:14:00 +0000 // Output 

I am not sure if I use these flags correctly, or NSDateFormatter is not converting my string correctly today.

Am I doing something wrong?

thanks

+6
source share
3 answers

+0000 at the end of the date indicates GMT. All dates are stored relative to GMT; when you convert a date to a string or vice versa, using the date format, your time zone offset is turned on. You can use the NSDateFormatter -setTimeZone: method to set the time zone used.

In short, you are not doing anything wrong with your code. Use [df stringFromDate:date]; to see that the date is correct. (You can also use NSDate -descriptionWithCalendarFormat:timeZone:locale: )

+12
source

try using

 df stringFromDate:date 

After working on mine,

 NSLog(@"Date for locale %@: %@", [[dateFormatter locale] localeIdentifier], [df stringFromDate:date]); 

gave me a conclusion like:

 Date for locale en_US: Wednesday, 26 June 2013 15:50 
0
source

Try setting the time zone and locale.

 [df setLocale:[NSLocale currentLocale]]; [df setTimeZone:[NSTimeZone systemTimeZone]]; 
-1
source

Source: https://habr.com/ru/post/905487/


All Articles