NSDateFormatter 和 yyyy-MM-dd

14
我想把格式为"2/22/11"的NSString类型日期转换成"2011-02-22"这种格式,以下是我的代码:
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 最初是一个 NSString 类型,等于 "2/22/11"。而 dateTemp 最终的值是 NIL。最终 newInvoice.date 的值也是 NIL。

我真的无法弄清楚为什么会这样。

2个回答

28
你遇到这个问题是因为你的日期格式化器不正确。假设你的newInvoice.date变量存储了"11:02:23",那么你的dateFormatter应该是@"yy:MM:dd",如果你的newInvoice.date变量存储了"2/22/11",那么你的dateFormatter应该是@"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];

两种格式都应根据您的要求进行,以获得正确的结果。


1

这应该可以正常工作。我已经设置了日期样式。您可以将NSDateFormatterShortStyle更改为其他内容。还要检查您的newInvoice.date格式。

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接