How to convert mail server date string to nsdate

I get a date string form mail server this way. Thu, 12.31.2009 14:32:15 +0580.
I want to convert this date string to date.

Here is my code:

- (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib. NSString * inputstring=@ "Mon, 3 sep 2012 08:32:39 +0580"; NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; [dateFormatter setDateFormat:@"EEE, dd MMM yyyy HH:mm:ss ZZZ"]; [dateFormatter setLenient:YES]; NSLocale *enUS = [[NSLocale alloc]initWithLocaleIdentifier:@"en_US"]; [dateFormatter setLocale:enUS]; NSDate *result = [dateFormatter dateFromString:inputstring]; NSLog(@"test==%@",result); } 

I get null output.

Excluded output: 2012-09-03 03:02:39 +0000

+4
source share
4 answers

First problem: you are not trying to read "Tue" in the line. (Add "EEE" at the beginning of your format)

The second and biggest problem: +0580 is not a valid time zone. A few years ago there was a PHP error that mistakenly returned IST (+0530) as +0580. 0580 does not make sense. This means 5 hours and 80 minutes. Thus, you can do one of two things: either replace +0580 with +0530 before processing it , or set the formatting date time zone to IST and remove +0580 from the line.

I see that you accepted a different answer, but this answer "works" because it cannot analyze the final part and ignore the time zone. I ran it and got 2013-07-09 08:32:38 +0000 (which does not match 2013-07-09 08:32:39 +0580 )

Deleting + in the accepted response format causes the formatting to be parsed correctly, but you will get null because the time zone is invalid. Changing the time zone to +0530 gives the expected result 2013-07-09 03:02:39 +0000

+2
source

Replace

[dateFormatter setDateFormat:@"d MMM yyyy HH:mm:ss ZZZ"];

with

[dateFormatter setDateFormat:@"EEE, dd MMM yyyy hh:mm:ss zzzz"];

+1
source

Just copy and paste the code below into your project and run it, see the result

 NSString *dateString = @"Tue, 9 Jul 2013 08:32:39 +0580"; NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; [dateFormatter setDateFormat:@"EEE, dd MM yyyy hh:mm:ss +zzzz"]; NSDate *dateFromString; dateFromString = [dateFormatter dateFromString:dateString]; NSLog(@"test==%@",dateFromString); 
+1
source

@Raviteja Kammila uses the following code for the date format, e.g. 2013-07-09 03:02:39 +0000

  NSString *dateString = @"Tue, 9 Jul 2013 08:32:39 +0580"; NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; [dateFormatter setDateFormat:@"EEE, dd MM yyyy HH:mm:ss +zzzz"]; NSDate *date = [dateFormatter dateFromString:dateString]; NSLog(@"final date : %@",date); 
+1
source

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


All Articles