开发者

NSDateFormatter and yyyy-MM-dd

I'm trying to take a NSString date in the format "2/22/11" and convert it to this format: 2011-02-22

This开发者_StackOverflow中文版 is my code:

NSDate *dateTemp = [[NSDate alloc] init];
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"yyyy-MM-dd"];
dateTemp = [dateFormat dateFromString:newInvoice.date];
newInvoice.date = [dateFormat stringFromDate:dateTemp];

newInvoice.date starts as an NSString equal to "2/22/11". dateTemp ends up NIL. newInvoice.date ends up NIL as well.

I can't for the life of me figure out why.


You are facing this problem because your date formatter is not correct.Suppose your newInvoice.date variable store "11:02:23" the your dateFormatter should be @"yy:MM:dd" and if your newInvoice.date variable store"2/22/11" then your dateFormatter should be @"MM/dd/yy"

NSDate *dateTemp = [[NSDate alloc] init];
NSDateFormatter *dateFormat1 = [[NSDateFormatter alloc] init];
NSDateFormatter *dateFormat2 = [[NSDateFormatter alloc] init];

[dateFormat1 setDateFormat:@"MM/dd/yy"];
[dateFormat2 setDateFormat:@"yyyy-MM-dd"];

dateTemp = [dateFormat1 dateFromString:newInvoice.date];
newInvoice.date = [dateFormat2 stringFromDate:dateTemp];

both format should be according to your requirement to get the correct result


This should work fine. I have set Date style. You can change NSDateFormatterShortStyle to something else. Also check your newInvoice.date format.

NSDate *dateTemp = [[NSDate alloc] init];

NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];

[dateFormat setDateStyle: NSDateFormatterShortStyle];

dateTemp = [dateFormat dateFromString: newInvoice.date];

[dateFormat setDateFormat:@"yyyy-MM-dd"];

newInvoice.date = [dateFormat stringFromDate:dateTemp];
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜