简体   繁体   English

将NSString转换为NSDate不起作用

[英]Converting NSString to NSDate is not working

I've read the DateFormatting guide and I'm still not able to get why my date conversion is not working as per requirement. 我已经阅读了DateFormatting指南,但我仍然无法理解为什么我的日期转换不符合要求。 For example: 例如:

NSString *str1 = @"12/20/2013 12:39:55 PM";
NSDateFormatter *dateFo = [[NSDateFormatter alloc] init];

[dateFo setDateFormat:@"MM/dd/YYYY hh:mm:ss a"];
NSDate *serverDate1 = [NSDate date];
serverDate1 = [dateFo dateFromString:str1];

In return I'm getting date as " 2013-01-05 07:09:55 +0000 ". 作为回报,我的日期为“ 2013-01-05 07:09:55 +0000 ”。 I have tried a lot why NSDate is not returning correct date. 我已经尝试了很多为什么NSDate没有返回正确的日期。

Any help would be appreciated. 任何帮助,将不胜感激。

Instead of YYYY use yyyy in your dateFormat: . 而不是YYYY在你的dateFormat:使用yyyy dateFormat: .

NSString *str1 = @"12/20/2013 12:39:55 PM";
NSDateFormatter *dateFo = [[NSDateFormatter alloc] init];

[dateFo setDateFormat:@"MM/dd/yyyy hh:mm:ss a"];
NSDate *serverDate1 = [NSDate date];
serverDate1 = [dateFo dateFromString:str1];
NSString *dateWithInitialFormat = @"12/20/2013 12:39:55 PM";
NSDateFormatter *dateFo = [[NSDateFormatter alloc] init];
[dateFo setDateFormat:@"MM/dd/yyyy hh:mm:ss a"];
NSDate *serverDate1 = [NSDate date];
serverDate1 = [dateFo dateFromString:dateWithInitialFormat];

This will get you your solution 这将为您提供解决方案

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

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