2012-03-30 9 views
1

私は奇妙なフォーマットの日付を含むデータベースから情報を引き出しています。私は、ユーザーのカレンダーに日付を追加するオプションを持っているEventKitを使用しようとしていますNSStringを解析して日付を見つけよう

のDayOfWeek、月日

:彼らは、彼らはの形式である引っ張られる

私はこれを行う最善の方法を見つけることができないようです。

正しい方向のヘルプやポイントは、非常にと非常に高く評価されます!

+0

あいまいな日付のデータベースです。プロジェクトは1年以上生きていないはずだと思います。それで幸運^^ –

答えて

1

このデータベースにはあいまいな日付があります。それは年の情報がありません。 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]); 
+0

ご協力いただきありがとうございます! – random

3

あなたはNSDateFormatterを使用したい:

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

「のDayOfWeek、月日には、」曖昧であるので、私はあなたが何を意味するのかを推測するために私のベストを尽くしました。私が間違っていた場合は、フォーマット文字列を少し変更する必要があります。 Here is a referenceを使用できます。

+0

それは私が探していたものです!私はEEEEの部分を見つけることができませんでした。そしてあいまいさを謝ります。 – random

+0

私は原因がわからないという奇妙なエラーがあります。上記のコードを使用してNSDateを取得します。しかし、EventKitで月を開き、数字の日付は正しいですが、日の日付(火など)は間違っています。 – random

+0

たとえば、「水曜日、5月9日」などの文字列を渡すとします。 EventKitに渡すと、 "Sat、May 9"が表示されます。 – random

関連する問題