iphone - 字符串格式的 Nsdate 不起作用

标签 iphone objective-c ios nsdate

我正在尝试将字符串日期转换为 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

有人可以帮我吗?

提前致谢!

最佳答案

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

[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

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

关于iphone - 字符串格式的 Nsdate 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9067216/

相关文章:

ios - AVAssetWriter 忽略变换值

iphone - NSUserDefaults 是否删除暂时不需要的 key ?

ios - 如何在具有多个组件的 UIPickerView 中为特定组件添加图像?

ios - NSMutableDictionary isKindOfClass NSDictionary 为 false

iphone - NSURLRequest 设置 HTTP header

iphone - 可以部分释放一 block 内存吗?

ios - CFRelease(CFArrayRef) 时崩溃

ios - CALayer 未实现自定义 drawLayer :inContext: method

ios - 初始化CBService时出错

iphone - 在 Objective C 中创建 epub 文件