2012-12-29 98 views
2

我有方法dateFromString一个问题,这里是我的代码NSDateFormatter dateFromString与日期

NSString* res = [NSString stringWithFormat:@"%@/%@/%@",dateInput.text,monthInput.text,yearInput.text]; 
NSDateFormatter* formatter = [[NSDateFormatter alloc]init]; 
[formatter setTimeZone:[NSTimeZone localTimeZone]]; 
[formatter setDateFormat:@"dd/MM/yy"]; 
NSDate* inpTime = [formatter dateFromString:res]; 
[dateResult setText:[NSString stringWithFormat:@"%@",inpTime]]; 

当我运行,日期在“inpTime”始终是“dateInput” - 1 例如:如果“ dateInput“为5,”inpTime“中的日期为4

+0

您的代码是完美的..没有错误!!!,请尝试清理目标。 –

回答

0

您需要调整时区。

变化

[formatter setTimeZone:[NSTimeZone localTimeZone]]; 

[formatter setTimeZone:[NSTimeZone timeZoneWithName:@"UTC"]]; 

这是因为你没有设置时间,所以它的默认设置午夜UTC。 但是,如果您使用UTC以外的时区显示日期,则会相应地移动时间。

就好像你住在纽约的2012年12月29日00:00:00 UTC实际上是2012年12月28日18:00:00给你一个例子。

+0

谢谢,我的问题解决了,你能解释为什么我需要将localTimeZone更改为timeZoneWithName:@“UTC”:D –

+0

有关说明,请查看我的更新答案。 –

+0

非常感谢:D –

0

你的代码是完美的,没有错误是如此之多。

尝试nslogging dateInput.text,monthInput.text和yearInput.text ...可能从这里获得无效数据。

+0

谢谢,我会再检查一次:D –

相关问题