NSDataFormatter dateFromString results in incorrec

2019-08-17 05:34发布

问题:

Here is my code :

[dateFormat setDateFormat:@"EEE MM d HH:mm:ss yyyy"];
logDate = [dateFormat dateFromString:[line substringToIndex:24]];    

line consist of string : "Mon Feb 18 09:25:53 2013: FAILED : Configuration-Update :"

I get the date alone "Mon Feb 18 09:25:53 2013" and formatted it with @"EEE MM d HH:mm:ss yyyy" format. I get an incorrect output : "2013-02-18 03:55:53 -0000" Time alone is printed incorrectly. I followed Date Format Patterns for specifying patters but still I am phasing this issue. I am not able to understand where it going wrong.. It would be helpful if someone finds the problem. thanks in advance

回答1:

Try this one

NSDate *date = [NSDate date];
NSDateFormatter * formatter = [[NSDateFormatter alloc]init];
[formatter setDateFormat:@"EEE MM d hh:mm:ss yyyy"];
NSLog(@"%@",[formatter stringFromDate:date]);
NSLog(@"%@",date);

When you just log using NSLog you get the UTC format (UTC consists of offset value, in India its standard time +5.30)that is yyyy-MM-d HH:mm:ss z , z is the offset added or subtracted to or from current time based on the locality.

For example

NSLog(@"%@",[formatter stringFromDate:date]);
NSLog(@"%@",date);

Tue 02 26 05:38:00 2013 //"EEE MM d hh:mm:ss yyyy"

Tue 02 26 17:46:22 2013 //"EEE MM d HH:mm:ss yyyy"

2013-02-26 12:08:00 +0000 //just logging using NSLog

Hope this helps you



回答2:

You'll need to set timezone for a NSDateFormatter when you print resulting date like this:

[formatter setTimeZone:[NSTimeZone localTimeZone]];


回答3:

You need to use as :

NSString *line=@"Mon Feb 18 09:25:53 2013: FAILED : Configuration-Update :";

NSDateFormatter *dateFormat=[NSDateFormatter new];
[dateFormat setDateFormat:@"EEE' 'MM' 'd' 'HH:mm:ss' 'yyyy"];

NSDate *logDate = [dateFormat dateFromString:[line substringToIndex:24]];

NSLog(@"logDate->%@",logDate);


回答4:

If we take the log of the NSdate object that will show the date with respect to the timezone +0000 only. for that we need to format the date to our local timezone. like this..

[dateFormat setDateFormat:@"EEE MM d HH:mm:ss yyyy"];
logDate = [dateFormat dateFromString:@"Mon Feb 18 09:25:53 2013"];
[dateFormat setTimeZone:[NSTimeZone localTimeZone]];
NSLog(@"Date %@",[dateFormat stringFromDate:logDate]);


回答5:

thanks to all.. it worked by changing the code this way ..

NSDateFormatter *dateFormat = [[[NSDateFormatter alloc] init]autorelease];
[dateFormat setDateFormat:@"EEE MM d HH:mm:ss yyyy"];    
[dateFormat setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"UTC"]];    
return [dateFormat dateFromString:dateString];