NSDateFormatter和yyyy-MM-dd [英] NSDateFormatter and yyyy-MM-dd
问题描述
我尝试以2/22/11格式获取NSString日期,并将其转换为以下格式:2011-02-22
I'm trying to take a NSString date in the format "2/22/11" and convert it to this format: 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。
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.
推荐答案
您遇到这个问题,因为您的日期格式化不正确。配置newInvoice.date变量存储11:02:23您的dateFormatter应该是@yy:MM:dd,如果您的newInvoice.date变量store2/22/11then your dateFormatter should be @MM / dd / yy
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
这篇关于NSDateFormatter和yyyy-MM-dd的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!