強火で進め

このブログではプログラム関連の記事を中心に書いてます。

ほぼ日、MacのGUI - Date Picker(日付の選択)

Date Pickerによる日付選択のサンプルです。NSDatePicker、NSDate、NSDateFormatterなどのクラスを主に使います。

選択した日付はNSDataのインスタンスに格納する形で取得します。

	NSDate *date = [datePicker dateValue];

NSDateFormatterを使い、整形して表示。今回は時間の部分は必要ないので NSDateFormatterNoStyle を設定し、表示させない。

	NSDateFormatter* formatter = [[[NSDateFormatter alloc] init] autorelease];

	// 選択した日付の表示
	[formatter setDateStyle:NSDateFormatterMediumStyle];
	[formatter setTimeStyle:NSDateFormatterNoStyle];
	NSLog(@"選択した日付      : %@", [formatter stringFromDate:date]);

選択した日付を基準に前日や翌日の日付を取得するには NSDate クラスの initWithTimeInterval:sinceDate: メソッドを使います。
initWithTimeInterval: に基準日に加える秒数を指定。 sinceDate: には基準日を設定します。

秒数は以下の様になります。

1分→60
1時間→60*60
1日→60*60*24

そのため前日を取得する場合は initWithTimeInterval: に -60*60*24 、翌日は 60*60*24 を指定します。

	// 前日の日付を取得
	lastDate = [[[NSDate alloc] initWithTimeInterval: -60*60*24 sinceDate:date] autorelease];
	NSLog(@"選択した日付の前日 : %@", [formatter stringFromDate:lastDate]);

	// 翌日の日付を取得
	nextDate = [[[NSDate alloc] initWithTimeInterval: 60*60*24 sinceDate:date] autorelease];
	NSLog(@"選択した日付の翌日 : %@", [formatter stringFromDate:nextDate]);

表示形式を変更するには NSDateFormatter クラスの setDateStyle: で設定します。
2008/01/02の場合のそれぞれの表示はこの様になります。

表示サンプル
NSDateFormatterShortStyle 08/01/02
NSDateFormatterMediumStyle 2008/01/02
NSDateFormatterLongStyle 2008年1月2日
NSDateFormatterFullStyle 2008年1月2日水曜日
	// 表示サンプル : 08/01/02
	[formatter setDateStyle:NSDateFormatterShortStyle];
	[formatter setTimeStyle:NSDateFormatterNoStyle];
	NSLog(@"NSDateFormatterShortStyle  : %@\n", [formatter stringFromDate:date]);

公式の解説はこちら。

NSDatePicker Class Reference
http://developer.apple.com/documentation/Cocoa/Reference/ApplicationKit/Classes/NSDatePicker_Class/Reference/Reference.html

NSDate Class Reference
http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSDate_Class/Reference/Reference.html

NSDateFormatter Class Reference
http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSDateFormatter_Class/Reference/Reference.html

日本語の解説が良い人はこちらのSatoshi Oomoriさんのページを参照下さい。

http://www.oomori.com/cocoafw/ApplicationKit/NSDatePicker/index.html

http://www.oomori.com/cocoafw/Foundation/NSDate/index.html

http://www.oomori.com/cocoafw/Foundation/NSDateFormatter/index.html
※注記
http://www.oomori.com/cocodesu/index.html

ソースコードこちら