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?
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:
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"MM/dd/YY w"];
NSDate *date = [dateFormatter dateFromString:@"1/5/13 1"];
NSLog(@"Date: %@", date);
Note that I'm using that capitalized form for the year. With 1 for the week of the year, I get this:
Date: 2013-01-05 08:00:00 +0000
and with 2 for the week of the year:
Date: 2013-01-12 08:00:00 +0000
and with 3:
Date: 2013-01-19 08:00:00 +0000
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?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With