Ankit Srivastava
Ankit Srivastava

Reputation: 12405

converting string to NSDate using NSDateFormatter returns in 1 year difference

I have a string date in UTC format:

"2012-11-20T05:23:02.34"

now I want the UTC NSDate object for this... and I implemented this function.

+ (NSDate *)utcDateFromString:(NSString *)string withFormat:(NSString *)format {
    NSDateFormatter *inputFormatter = [[NSDateFormatter alloc] init];
    inputFormatter.timeZone =[NSTimeZone timeZoneWithAbbreviation:@"UTC"];
    [inputFormatter setDateFormat:format];
    NSDate *date = [inputFormatter dateFromString:string];
    [inputFormatter release];
    return date;
}

and called it like this...

NSDate* submittedDate =[NSDate utcDateFromString:submittedDateString withFormat:@"YYYY-MM-dd'T'HH:mm:ss.SS"];

but this returns the NSDate description as this..

2011-11-20 05:23:02 +0000

Now if you notice there is one year difference in the dates... can anyone explain why is this happening..?

Thanks for your help.

Upvotes: 1

Views: 549

Answers (2)

Paras Joshi
Paras Joshi

Reputation: 20541

try this bellow method..

-(NSDate *)getUTCFormateDate:(NSString *)localDate withFormat:(NSString *)format 
{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:format];
    NSTimeZone *timeZone = [NSTimeZone timeZoneWithName:@"UTC"];
    [dateFormatter setTimeZone:timeZone];
    NSDate *date = [dateFormatter dateFromString:localDate];
    return date;        
}

And Use Like bellow..

    NSDate *dateHere = [[NSDate alloc]init];
    dateHere = [self getUTCFormateDate:@"2012-11-20T05:23:02.34" withFormat:@"yyyy-MM-dd'T'HH:mm:ss.SS"];
    NSLog(@"Date here %@",dateHere);

and i get output is Date here 2012-11-20 05:23:02 +0000

see my another answer which return string date with UTF format..

convert NSstring date to UTC dateenter link description here

Upvotes: 1

Ilanchezhian
Ilanchezhian

Reputation: 17478

in the dateformmater, use yyyy instead of YYYY

It should be

NSDate* submittedDate =[NSDate utcDateFromString:submittedDateString withFormat:@"yyyy-MM-dd'T'HH:mm:ss.SS"];

That will solve the problem.

In the following link, search for YYYY.

https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/DataFormatting/Articles/dfDateFormatting10_4.html

It uses yyyy to specify the year component. A common mistake is to use YYYY. yyyy specifies the calendar year whereas YYYY specifies the year (of “Week of Year”), used in the ISO year-week calendar. In most cases, yyyy and YYYY yield the same number, however they may be different. Typically you should use the calendar year.

Upvotes: 5

Related Questions