开发者

Convert String to NSDate

I am trying to convert a string which is of the format August 1, 2011 to a NSDate.

I used the following code

NSString *dateStr = @"Aug 3, 2011";

// Convert string to date object
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"MMMM d, YYYY"];
NSDate *date = [dateFormat dateFromString:dateStr];  

[picker setD开发者_运维百科ate:date animated:YES];

But the output is get is not the December 26, 2010 in the date picker.


Regarding your comment on Bertrand Marron's answer, if you are sure you have the date formatter right, perhaps the problem is with your picker? Can you check the value of the date in the debugger and confirm that is correct? Is your picker a custom subclass or the standard date picker?

EDIT:

After reproducing this myself, I have the answer.

Replace

[dateFormat setDateFormat:@"MMMM d, YYYY"];

with

[dateFormat setDateFormat:@"MMMM d, yyyy"];

Upper case YYYY indicates "Week of year" in the ISO year-week calendar. See documentation for data formatting guide --> Date formatters for example.


I think you should specify:

[dateFormat setDateFormat:@"MMM d, YYYY"];

Have also a look at this document:

Month - Use one [M] or two for the numerical month, three for the abbreviation, or four for the full name, or five for the narrow name.

(The "narrow name" is something like the initial of the month; you are looking for the abbreviation)


try this it may use

[dateFormat setDateFormat:@"MMM d, YYYY"];


Your date is not formatted like "August 1, 2011".

NSString *dateStr = @"Aug 3, 2011";

The correct format string would be @"MMM d, YYYY"

Although @"MMMM d, YYYY" would work for @"August 1, 2011".


NSDateFormatter* formatter = [[[NSDateFormatter alloc] init] autorelease];// autorelease    
[formatter setDateFormat:@"MMM d, YYYY hh:mma"];
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜