Reputation: 151
I'm letting the user input a date into a UITextField. When I format the string and output it in a NSLog statement, I am getting an incorrect value for the date. For instance, when I input 11-16-2011 11:43 into the text field, I get 2010-12-26 16:43:00 +0000 in the log. My code is as follows:
NSString *dateString = dateTextField.text;
//create a NSDateFormatter that can be used to create a NSDate from the string
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"MM-dd-YYYY hh:mm"];
[formatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:-18000]];
//create a NSDate from the string using our formatter
NSDate *alertTime = [formatter dateFromString:dateString];
NSLog(@"dateString is %@", alertTime);
[formatter release];
Thanks!
Upvotes: 0
Views: 82
Reputation: 4879
use yyyy for year. From the doc http://developer.apple.com/library/ios/#documentation/Cocoa/Conceptual/DataFormatting/Articles/dfDateFormatting10_4.html#//apple_ref/doc/uid/TP40002369-SW1:
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.
Also:
h Hour [1-12].
H Hour [0-23].
Upvotes: 1
Reputation: 2836
Louie's answer is correct - but consider using a UIDatePicker for user date input instead.
Upvotes: 0
Reputation: 5940
I had something simular happen to me about a week ago. After a little digging I had to change my format around from a couple of lowercase characters to Uppercase.
Not sure if this will work but try changing
[formatter setDateFormat:@"MM-dd-YYYY hh:mm"];
to this:
[formatter setDateFormat:@"MM-dd-yyyy HH:mm"];
P.S... you might get more answers if you start to accept the answers that helped you. :)
Upvotes: 2