【问题标题】:NSString parse to find dateNSString 解析以查找日期
【发布时间】:2012-03-30 22:34:09
【问题描述】:

我正在从包含格式奇怪的日期的数据库中提取信息。

当它们被拉出时,它们的格式为:

DayOfWeek,月份日期

我正在尝试使用 EventKit 来选择将日期添加到用户日历。

我似乎找不到执行此操作的最佳方法。

任何帮助或指出正确的方向都将非常感谢非常!

【问题讨论】:

  • 日期不明确的数据库。我猜这个项目不应该存在超过一年。祝你好运^^

标签: objective-c ios xcode nsstring eventkit


【解决方案1】:

您想使用NSDateFormatter:

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
dateFormatter.dateFormat = @"EEEE, MMMM d";
NSDate *date = [dateFormatter dateFromString:@"Tuesday, March 3"];

“DayOfWeek, Month Date”是模棱两可的,所以我尽力猜测你的意思。如果我错了,您需要稍微更改格式字符串。 Here is a reference 在您可以使用的字符串上。

【讨论】:

  • 这就是我要找的!我找不到 EEEE 部分。对于含糊不清的地方,我深表歉意。
  • 我有一个奇怪的错误,我不确定原因。我使用上面的代码拉到 NSDate。但是,当我使用 EventKit 打开它时,月份和数字日期是正确的,但日期(例如星期二 ..)是错误的。
  • 例如,如果我传入一个字符串,例如“5 月 9 日,星期三”。当我将它传递给 EventKit 时,它会显示“Sat, May 9”。
  • 日期格式化程序会根据您提供的信息尽其所能。由于工作日不提供超出月份和日期的任何信息,因此它会忽略它,而只给出今年的月份和日期。因此,完全有可能获得不同的工作日。
  • 今年不用。它使用 1970 年。令人惊讶的是,1970 年 5 月 9 日是星期六。如果你想解析“March”,最好将语言环境设置为@“en_US”。
【解决方案2】:

您的问题是该数据库的日期不明确。它没有年份信息。 NSDateFormatters 不会猜测日期信息。他们根据您提供的信息创建日期。由于缺少此信息,因此年份将是 1970 年(如:与参考数据相同的年份)。

因为保存在数据库中的格式完全是愚蠢的,我假设这些日期总是在接下来的 365 天内。所以理论上你不必保存一年的信息。
然后,您可以使用类似的方法从完全模棱两可的日期信息中找出 NSDate。
这个想法是将日期从 1970 年(从您的字符串创建)转移到当前年份。如果它是当年的过去(例如,今天是 3 月 31 日,“Foo,3 月 30 日”的日期将是过去)将其移至明年。

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
dateFormatter.dateFormat = @"EEEE, MMMM d";
// the following line is important if you want that your code runs on device that are not english!
dateFormatter.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US"];
NSDate *date = [dateFormatter dateFromString:@"Wednesday, March 30"];
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *components = [calendar components:NSMonthCalendarUnit|NSDayCalendarUnit fromDate:date];

NSDateComponents *todayComponent = [calendar components:NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit fromDate:[NSDate date]];

NSInteger proposedYear = [todayComponent year];
// if supposed date would be in the past for the current year move it into next year
if ([components month] < [todayComponent month]) {
    proposedYear++;
}
if ([components month] == [todayComponent month] && [components day] < [todayComponent day]) {
    proposedYear++;
}
[components setYear:proposedYear];

date = [calendar dateFromComponents:components];


// just for logging, so you are sure that you use the correct year:
[dateFormatter setDateFormat:@"EEEE, MMMM d yyyy"];
NSLog(@"%@", [dateFormatter stringFromDate:date]);

【讨论】:

    猜你喜欢
    • 2021-05-25
    • 1970-01-01
    • 1970-01-01
    • 2016-05-24
    • 2012-02-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多