0

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!

3 Answers 3

2

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. :)

Sign up to request clarification or add additional context in comments.

Comments

1

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].

Comments

0

Louie's answer is correct - but consider using a UIDatePicker for user date input instead.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.