我使用以下代码格式化日期格式,例如“MM / dd / YYYY”
NSDateFormatter *dateFormatter=[[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"MM/dd/YYYY"];
NSString *dateString=[dateFormatter stringFromDate:[NSdate date]];
NSString *dbDate=@"08/03/2013";
NSDate *currentDate=[dateFormatter dateFromString:dateString];
NSDate *newDate=[dateFormatter dateFromString:dbDate];
NSLog(@"currentDate is %@",currentDate);
NSLog(@"newDate is %@",newDate);
但是我得到的控制台输出如下
currentDate是2013-01-04 18:30:00 +0000
newDate是2013-01-04 18:30:00 +0000
但我期待输出如下
currentDate是11/22/2013
newDate是08/03/2013
任何人都可以纠正我的错误
提前致谢
答案 0 :(得分:1)
NSDate的NSLog始终采用以下格式:
yyyy-MM-dd HH:mm:ss +timezone
2012-12-23 18:30:00 +0000
如果您想要11/22/2013
格式,则需要将日期转换为NSString
并记录该字符串。
此外,您有几个错误,请使用此代码:
NSDateFormatter *dateFormatter=[[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"MM/dd/yyyy"];
NSString *dateString=[dateFormatter stringFromDate:[NSDate date]];
NSString *dbDate=@"08/03/2013";
NSDate *currentDate=[dateFormatter dateFromString:dateString];
NSDate *newDate=[dateFormatter dateFromString:dbDate];
NSLog(@"currentDate is %@",[dateFormatter stringFromDate:currentDate]);
NSLog(@"newDate is %@",[dateFormatter stringFromDate:newDate]);
输出:
currentDate is 11/22/2013
newDate is 08/03/2013
答案 1 :(得分:0)
您需要格式化要显示的字符串:
NSLog(@"currentDate is %@",[dateFormatter stringFromDate: currentDate]);
您的日期格式应为:
[dateFormatter setDateFormat:@"MM/dd/yyyy"];
答案 2 :(得分:0)
使用以下代码。无需将[NSDate date]转换为字符串,然后返回NSDate,然后返回字符串进行输出。
你也写了YYY而不是yyyy
NSDateFormatter *dateFormatter=[[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"MM/dd/yyyy"];
NSString *dbDate=@"08/03/2013";
NSDate *currentDate = [NSDate date];
NSDate *newDate=[dateFormatter dateFromString:dbDate];
NSLog(@"currentDate is %@",[dateFormatter stringFromDate:currentDate]);
NSLog(@"newDate is %@",[dateFormatter stringFromDate:newDate]);