【问题标题】:NSString datetime to NSDate [duplicate]NSString datetime 到 NSDate [重复]
【发布时间】:2013-05-29 16:17:14
【问题描述】:

我很难将 NSString 转换为 NSDate。我尝试了很多日期格式,但都没有成功。

我的字符串是: 2013 年 5 月 17 日上午 12:00:00

我正在使用:

NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"M/d/y hh:mm:ss a"];
[dateFormat setTimeZone:[NSTimeZone timeZoneWithName:@"GMT"]];
NSDate *cI = [dateFormat dateFromString:@"5/17/2013 2:00:00 AM"];
[dateFormat release];

我也尝试过:

  • 月/日/年 h:mm:ss a
  • 月/日/年 hh:mm:ss
  • 月/日/年 h:mm:ss

但 cI 总是为零。

【问题讨论】:

  • 您何时/何地记录“cI”。您是在 dateFromString 之后立即对其进行 NSLogging,还是在其他地方?
  • 再一次,你在哪里记录“cl”???你怎么知道在 dateFromString 操作之后它是 nil ??

标签: objective-c nsstring nsdate nsdateformatter


【解决方案1】:

用途:

NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"MM/dd/yyyy hh:mm:ss a"];
[dateFormat setTimeZone:[NSTimeZone timeZoneWithName:@"GMT"]];
NSDate *cI = [dateFormat dateFromString:@"5/17/2013 2:00:00 AM"];
[dateFormat release];

输出:2013-05-17 02:00:00 +0000

【讨论】:

  • Anoop,我正在复制并粘贴你的代码,我得到一个
  • @Tony:正如你在屏幕截图中看到的那样,它正在工作!!!
  • setDateFormat 在消息和屏幕中是不同的。任何方式我都尝试但没有工作。可能是在我的环境中有所不同。
  • 是的,只是为了向您展示,即使这样也有效....即使您的代码也很好。尝试清理并重新构建。
  • cough 不要忘记设置 en_US_POSIX 语言环境(请参阅developer.apple.com/library/ios/#qa/qa1480/_index.html)
【解决方案2】:

在这里,它在我的语言环境中运行良好 @"MM/dd/YYYY h:mm:ss a"

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-05-11
    • 2013-01-16
    • 2012-12-17
    • 2018-03-10
    • 2014-01-18
    • 2011-02-06
    相关资源
    最近更新 更多