如何将字符串转换为日期以及从字符串转换日期?
我的输入字符串是
NSString *inputString=@"15 February 2012 17:05";
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"dd MMMM YYYY HH:mm"];
NSDate *dateVal = [dateFormat dateFromString:inputString];
NSDateFormatter *dateFormat2 = [[NSDateFormatter alloc] init];
[dateFormat2 setDateFormat:@"MM/dd/YYYY HH:mm"];
NSString *outputString = [dateFormat2 stringFromDate:dateVal];
[dateFormat release];
[dateFormat2 release];
我得到以下日期 outputString=12/25/2011 17:05
但应该是02/15/2012 17:05..我在哪里做错了?
My Input String is
NSString *inputString=@"15 February 2012 17:05";
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"dd MMMM YYYY HH:mm"];
NSDate *dateVal = [dateFormat dateFromString:inputString];
NSDateFormatter *dateFormat2 = [[NSDateFormatter alloc] init];
[dateFormat2 setDateFormat:@"MM/dd/YYYY HH:mm"];
NSString *outputString = [dateFormat2 stringFromDate:dateVal];
[dateFormat release];
[dateFormat2 release];
I got the following date
outputString=12/25/2011 17:05
But it should be 02/15/2012 17:05..Where did i do the mistake?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
日期格式不正确,请使用:
大写“YYYY”用于基于“一年中的周”的日历。
请参阅:unicode Date_Format_Patterns
顺便说一句,
NSLog
的dateVal
会表明问题出在输入格式上。The date format is incorrect, use:
Capital "YYYY" is for use in "Week of Year" based calendars.
See: unicode Date_Format_Patterns
BTW, an
NSLog
ofdateVal
would have shown that the problem was on the input formatting.您使用的日期格式错误,也无需创建 NSDateFormatter 的另一个实例 -
You are using wrong format for date format and also there is no need to create another instance of NSDateFormatter -
您的区域设置是否与您尝试解析的格式相对应?默认情况下,NSDateFormatter 使用当前区域设置。
Does your locale correspond to the format you are trying to parse? By default NSDateFormatter uses current locale.
输入日期格式应为:
The input date format should be: