使用 NSDateFormater 从字符串中获取日期时如何忽略某些字符?另外,是否有 NSDateFormatter 的参考资料?

How do I ignore some characters when getting date from string using NSDateFormater? Also, is there any reference for NSDateFormatter?

我的问题很简单。我的字符串格式为“2015 年 9 月 16 日”

在生成日期字符串时,我使用 NSDateFormatter 作为 "d MMM yyyy",然后手动修改它以使用 switch case 插入日期后缀。

现在,我需要再次提取日期。

有什么办法可以忽略这两个字母吗?

此外,我一直在通过使用 Google 学习 NSDateFormatter 并关注 this 等帖子,但我的所有问题都没有得到解答,有时,描述的行为不匹配。

Apple 是否有描述日期格式化程序代码的标准参考?

恐怕只是部分答案,但 Apple 基本上实现了这个规范:http://www.unicode.org/reports/tr35/tr35-31/tr35-dates.html#Date_Format_Patterns

该规范确实建议了一种叫做 "Lenient parsing" 的东西,它允许解析器忽略一些无关的字符,但至少按照标准中的定义,这似乎并没有扩展到您的特定情况。所以看起来你必须在将字符串交给解析器之前手动删除天数的后缀,除非它碰巧 "just work",我认为它不会。

这是日期格式正确的代码,将成为您的天使:

NSDateFormatter *df = [[NSDateFormatter alloc] init];
df.dateFormat = @"d'th' MMM yyyy";

NSString *stringDate = [df stringFromDate:[NSDate date]];

//output -- 16th Sep 2015

现在您可以使用此日期格式化程序与 NSDate 对象相互转换。

NSDateformatter 不支持带序数指示符的日期,但您可以使用正则表达式去除指示符

var dateString = "16th Sep 2015"
if let range = dateString.range(of: "(st|nd|rd|th)", options: .regularExpression) {
    dateString.removeSubrange(range)
}    
let formatter = DateFormatter()
formatter.locale = Locale(identifier: "en_US_POSIX")
formatter.dateFormat = "dd MMM yyyy"
let date = formatter.date(from: dateString)!
print(date)

或在Objective-C

NSMutableString *dateString = [NSMutableString stringWithString:@"16th Sep 2015"];

NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"(st|nd|rd|th)" options:nil error:nil];
[regex replaceMatchesInString:dateString options: nil range: NSMakeRange(0, 4) withTemplate:@""];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
formatter.dateFormat = @"d MMM yyyy";
NSDate *date = [formatter dateFromString:dateString];
NSLog(@"%@", date);

这不是最漂亮的解决方案,但它可以工作:

NSString *dateString = @"1st Sep 2015";

dateString = [dateString stringByReplacingOccurrencesOfString:@"st " withString:@" "];
dateString = [dateString stringByReplacingOccurrencesOfString:@"nd " withString:@" "];
dateString = [dateString stringByReplacingOccurrencesOfString:@"rd " withString:@" "];
dateString = [dateString stringByReplacingOccurrencesOfString:@"th " withString:@" "];

NSDateFormatter *df = [[NSDateFormatter alloc] init];
df.dateFormat = @"d MMM yyyy";

NSDate *date = [df dateFromString:dateString];

虽然如果您有 3 个字母的月份,它会起作用,但如果您有完整的月份,它就不会起作用。例如,"Augu" 将变成 "August" 使用正则表达式,您可以通过执行以下操作来检查字母之前的数字:

var dateString = "16th Sep 2015"
//regular expression using positive look behind. Checks for a digit, than a two letter combination that will match below
dateString = dateString.replacingOccurrences(of: "(?<=\d)[snrt][tdh]", with: "", options: String.CompareOptions.regularExpression, range: nil)

let df = DateFormatter()
df.dateFormat = "d MMM yyyy" //if full month, add extra M
df.date(from: dateString)