【问题标题】:NSDate from NSString来自 NSString 的 NSDate
【发布时间】:2026-02-04 00:10:01
【问题描述】:

我有一个格式为“Fri Jul 09 17:57:44 +0000 2010”的字符串,我需要将其转换为 NSDate。

我尝试了一些不成功的操作来转换这个日期,想知道是否有人可以告诉我如何实现这一点。

问候

【问题讨论】:

标签: cocoa nsstring nsdate format-specifiers


【解决方案1】:

你试过暴力破解方法吗:

这是未经测试的,但应该让您知道该怎么做。

// Set up some helper information
NSArray *monthArray = [NSArray arrayWithObjects:@"Jan", @"Feb", @"Mar",
                                                @"Apr", @"May", @"Jun",
                                                @"Jul", @"Aug", @"Sep",
                                                @"Oct", @"Nov", @"Dec", nil];
NSArray *ordinalArray = [NSArray arrayWithObjects:@"01", @"02", @"03",
                                                  @"04", @"05", @"06",
                                                  @"07", @"08", @"09",
                                                  @"10", @"11", @"12", nil];

NSDictionary *monthOrdinalDictionary = [NSDictionary dictionaryWithObjects:ordinalArray 
                                                         forKeys:monthArray];

// This is the date string to convert.
dateString = @"Fri Jul 09 17:57:44 +0000 2010"; 

// Split it into it's components
NSArray *dateComponentArray = [dateString componentsSeparatedByString:@" "];

// Create a new date string from the components in a format that NSDate understands
newDateString = [NSString stringWithFormat:@"%@-%@-%@ %@ %@", [dateComponentArray objectAtIndex:6],
                                   [monthOrdinalDictionary objectForKey:[dateComponentArray objectAtIndex:2]],
                                   [dateComponentArray objectAtIndex:3],
                                   [dateComponentArray objectAtIndex:4],
                                   [dateComponentArray objectAtIndex:5]];

// Create the date from this string
NSDate *dateTime = [NSDate dateWithString:newDateString];

是的,它很丑陋,但您可以将其中的大部分重构为辅助函数。我还没有测试过,但是你应该知道该怎么做:获取日期字符串,将其转换为 NSDate 可用于创建日期的字符串,使用此字符串创建 NSDate。

至少你会有代码可以处理,如果它是性能瓶颈,你可以返回并更改它。

【讨论】:

  • 只是一个通过块工作的例子。使用dateWithNaturalLanguageString:locale 可能会起作用(我还没有尝试过)。我想展示一种在尝试开发应用程序时通过块工作的方法,以便在返回和优化代码之前让它工作。