NSDateFormatter不会在NSDate中转换我的NSString [英] NSDateFormatter doesn't convert my NSString in NSDate

查看:97
本文介绍了NSDateFormatter不会在NSDate中转换我的NSString的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个字符串,需要将其转换为日期,但不能正确转换.我不知道为什么...我的代码是:

I have a string and need convert it to a date, but it doesn't convert correctly. I don't know why... my code is:

NSString * fecha = @"2011-12-07 11:11:29.657";

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss.ZZZ"];

NSDate *dateFromString = [[NSDate alloc] init]; 
dateFromString = [dateFormatter dateFromString:fecha]; 

NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
unsigned units = NSYearCalendarUnit | NSMonthCalendarUnit |  NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit;

NSDateComponents *components = [calendar components:units              
                                           fromDate:dateFromString];
 NSInteger* hour = [components hour];
 NSInteger* minute = [components minute];
 NSInteger* second = [components second];  

NSLog(@"Fecha: %@",fecha);
NSLog(@"Format: %@",dateFormatter.dateFormat);
NSLog(@"date: %@",dateFromString);

在我的日志中:

2011-12-07 11:36:11.750 Catalogo-V1[13741:207] Fecha: 2011-12-07 11:11:29.657
2011-12-07 11:36:11.750 Catalogo-V1[13741:207] Format: yyyy-MM-dd HH:mm:ss.ZZZ
2011-12-07 11:36:11.751 Catalogo-V1[13741:207] date: (null)

推荐答案

我认为,您将需要yyyy-MM-dd HH:mm:ss.SSS而不是格式字符串yyyy-MM-dd HH:mm:ss.ZZZ.

I think that instead of the format string yyyy-MM-dd HH:mm:ss.ZZZ, you will want yyyy-MM-dd HH:mm:ss.SSS.

ZZZ是时区值,而SSS是小数秒.

ZZZ will be a timezone value, whereas SSS is fractional seconds.

请参见 Unicode文档(与数据格式)

另一件事:您不需要行NSDate *dateFromString = [[NSDate alloc] init];.只需调用NSDate *dateFromString = [dateFormatter dateFromString:fecha];.日期格式化程序将根据需要分配日期对象.

one other thing: you don't need to have the line NSDate *dateFromString = [[NSDate alloc] init];. Just call NSDate *dateFromString = [dateFormatter dateFromString:fecha];. The date formatter will allocate the date object as it needs to.

这篇关于NSDateFormatter不会在NSDate中转换我的NSString的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆