【问题标题】:Nsdate from string format not working来自字符串格式的 Nsdate 不起作用
【发布时间】:2012-02-22 10:40:09
【问题描述】:

我正在尝试将字符串日期转换为 NSDate 以对格式进行一些更改.. 但它总是返回 nil!

这是我的代码:

NSDateFormatter *df = [[NSDateFormatter alloc] init];

//Mon Jan 30 17:40:12 +0000 2012
[df setDateFormat:@"ccc MMM dd HH:mm:ss Z yyyy"];
[df setTimeStyle:NSDateFormatterFullStyle];
[df setFormatterBehavior:NSDateFormatterBehavior10_4];
[df setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"en_US"]];

NSDate *date1 = [df dateFromString:strData];

我也试过这种格式:

[df setDateFormat:@"EEE MMM dd HH:mm:ss z yyyy"];

我试过这张桌子:

http://www.deanoj.co.uk/ios-development/nsdateformatter-formatting-strings-reference/

我已经尝试过这些链接.. 以及很多其他链接:

Convert NSString to NSDate with string format "Sun, 08 Jan 2012 13:57:38 +0000"

NSDateFormatter dateFromString returns nil

How to format Facebook/Twitter dates (from the JSON feed) in Objective-C

有人可以帮帮我吗?

提前致谢!

【问题讨论】:

  • 别忘了释放分配的NSLocale,否则会泄露

标签: iphone objective-c ios nsdate


【解决方案1】:

如果我把你的代码修改成这样:

[df setDateFormat:@"ccc MMM dd HH:mm:ss Z yyyy"];
// [df setTimeStyle:NSDateFormatterFullStyle];
// [df setFormatterBehavior:NSDateFormatterBehavior10_4];
[df setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"en_US"]];

NSDate *date1 = [df dateFromString:@"Mon Jan 30 17:40:12 +0000 2012"];
NSLog( @"date is %@", date1);

我明白了:

2012-01-30 11:36:38.339 TestApp[32182:f803] date is 2012-01-30 17:40:12 +0000

似乎您需要做的就是注释(或删除)这两行。

【讨论】:

  • 是的..这是真的..我不知道我为什么这样做..非常感谢哥们!
猜你喜欢
  • 1970-01-01
  • 2011-06-23
  • 2023-03-18
  • 2014-04-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-06-18
  • 1970-01-01
相关资源
最近更新 更多