On my machine (regional settings United States), the default "short" date format is set to "1/5/13" (month/day/year).
In the System Preferences, I have appended to it a week number, "1/5/13 1".
My problem is this code, where I try to convert a string to a date:
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateStyle:NSDateFormatterShortStyle];
NSDate *date = [dateFormatter dateFromString:@"1/5/13 1"];
NSLog(@"Date: %@", date);
On my machine, this prints:
Date: 2000-01-01 05:00:00 +0000
That's 2000, which is not even close to 2013.
What is causing this problem?
You need to use
dateFromString
method ofNSDateFormatter
...If you want to play with week number then use
NSCalendar
andNSDateComponents
based on your need... (refer this code snippet)I hope this helps.
I'm late to this discussion, and have seen a number of solutions offered, but what I see wrong with them all is that two incompatible date format elements are being used together. Your original approach failed because the string from which you're attempting to get your date doesn't match what
NSDateFormatterShortStyle
provides for.If you're going to evaluate the week of the year, then you've got to use the capitalized form of the year; this provides for a "Week of Year" kind of calendar.
Let's re-work your original code a bit to include the new format:
Note that I'm using that capitalized form for the year. With 1 for the week of the year, I get this:
and with 2 for the week of the year:
and with 3:
Makes sense, doesn't it? The day in the date increments by seven days with each increment by one of the week of year. The time's dorked, of course, but we never discussed anything to evaluate in that area, did we?