私は奇妙なフォーマットの日付を含むデータベースから情報を引き出しています。私は、ユーザーのカレンダーに日付を追加するオプションを持っているEventKitを使用しようとしていますNSStringを解析して日付を見つけよう
のDayOfWeek、月日
:彼らは、彼らはの形式である引っ張られる
。
私はこれを行う最善の方法を見つけることができないようです。
正しい方向のヘルプやポイントは、非常にと非常に高く評価されます!
私は奇妙なフォーマットの日付を含むデータベースから情報を引き出しています。私は、ユーザーのカレンダーに日付を追加するオプションを持っているEventKitを使用しようとしていますNSStringを解析して日付を見つけよう
のDayOfWeek、月日
:彼らは、彼らはの形式である引っ張られる
。
私はこれを行う最善の方法を見つけることができないようです。
正しい方向のヘルプやポイントは、非常にと非常に高く評価されます!
このデータベースにはあいまいな日付があります。それは年の情報がありません。 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]);
ご協力いただきありがとうございます! – random
あなたはNSDateFormatter
を使用したい:
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
dateFormatter.dateFormat = @"EEEE, MMMM d";
NSDate *date = [dateFormatter dateFromString:@"Tuesday, March 3"];
「のDayOfWeek、月日には、」曖昧であるので、私はあなたが何を意味するのかを推測するために私のベストを尽くしました。私が間違っていた場合は、フォーマット文字列を少し変更する必要があります。 Here is a referenceを使用できます。
あいまいな日付のデータベースです。プロジェクトは1年以上生きていないはずだと思います。それで幸運^^ –