Karamjeet Singh
Karamjeet Singh

Reputation: 490

Issue in NSDateFormatter converting NSDate into string

Today one of my client report a bug that one of the application functionality suddenly stop work. After I unit-test the functionality, I come to know that NSDateFormatter is converting a wrong date. May be you had also experienced the same. below is my code

 self.frmt2=[[NSDateFormatter alloc]init];
 [self.frmt2 setDateFormat:@"YYYY-MM-dd”];
 self.str_DateTogetData=[self.frmt2 stringFromDate:[NSDate date]];

If my system date is between 29-12-2014,30-12-2014,31-12-2014, then after converting date into string its shows 29-12-2015,30-12-2015,31-12-2015 but if my system date is not between these three dates then above code convert NSDate into string correctly.but if I am using below code then its converting NSDate into string correctly

 self.frmt2=[[NSDateFormatter alloc]init];
 [self.frmt2 setDateFormat:@"yyyy-MM-dd”];
 self.str_DateTogetData=[self.frmt2 stringFromDate:[NSDate date]];

My problem is solved but I am in seek of knowledge why its happen. Any one have answer of it.

Upvotes: 1

Views: 441

Answers (3)

Chandu kumar.Alasyam
Chandu kumar.Alasyam

Reputation: 722

-small mistake in your date formatter

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

your date formatter should be in this formate [self.frmt2 setDateFormat:@"yyyy-MM-dd"]

Upvotes: 1

gnasher729
gnasher729

Reputation: 52632

Your "knowledge" that YYYY and yyyy are the same is totally wrong.

It has been explained several times in this thread that they are not the same, and now you have actually updated your question to say that they are the same. They are not.

Did you understand at all what YYYY is for? It is for situations where you number weeks. Week 1 of 2014, week 2 of 2014, and so on. The week from Monday, 29th Dec 2014 to Sunday, 4th March 2015 is one week, and because four of its days are in 2015, it's the first week of 2015.

Upvotes: 0

arthankamal
arthankamal

Reputation: 6413

yyyy specifies the calendar year, whereas YYYY specifies the year (of “Week of Year”).

From Date Formatter Documentation, check the last 2 points from Use Format Strings to Specify Custom Formats section

Upvotes: 4

Related Questions