简体   繁体   English

NSDateFormatter dateFromString与日期

[英]NSDateFormatter dateFromString with date

i have a problem with method dateFromString, here is my code 我对方法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]];

when I run, the date in "inpTime" always is "dateInput" - 1. for example: if "dateInput" is 5, the date in "inpTime" will be 4 当我运行时,“ inpTime”中的日期始终为“ dateInput” -1。例如:如果“ dateInput”为5,则“ inpTime”中的日期为4

You need to adjust the timezone. 您需要调整时区。

Change 更改

[formatter setTimeZone:[NSTimeZone localTimeZone]];

to

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

This is because you're not setting the time, so it's set by default the midnight UTC. 这是因为您没有设置时间,所以默认设置为午夜UTC。 But when you are displaying the date with a timezone other than UTC the time is shifted accordingly. 但是,当您使用非UTC时区显示日期时,时间也会相应地移动。

As an example if you live in New York the 12/29/2012 00:00:00 UTC is actually the 12/28/2012 18:00:00 for you. 例如,如果您居住在纽约,那么12/29/2012 00:00:00 UTC实际上就是您的12/28/2012 18:00:00

You Code is perfect, no error what so ever. 您的代码是完美的,没有错误。

Try nslogging dateInput.text, monthInput.text and yearInput.text...might be from here you are getting invalid data. 尝试nslogging dateInput.text,monthInput.text和yearInput.text ...可能从此处获取无效数据。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM