NSCalendar *変数 = [NSCalendar currentCalondar];こうして得られたカレンダー情報から、さまざまな日時の情報を扱えるようになります。まず、日時の細かな値を調べてみましょう。これはcomponents: fromDate:というメソッドを利用します。
NSDateComponents *変数 = [《NSCalendar*》 components:《NSCalendarUnit》引数には、取り出したいカレンダーユニット(カレンダーの日時データの要素)と、日時を示すNSDateが渡されます。このうち、ちょっと説明が必要なのはカレンダーユニットでしょう。これは日時のどの値を取り出したいかを示す値で、以下のいずれかが利用できます。
fromDate:《NSDate*》];
NSEraCalendarUnit ――時代を示す値(紀元前・紀元後など)これらの中で必要なものをcomponents:で指定します。複数の項目を指定する場合は、
NSYearCalendarUnit ――年の値
NSMonthCalendarUnit ――月の値
NSDayCalendarUnit ――日の値
NSHourCalendarUnit ――時の値
NSMinuteCalendarUnit ――分の値
NSSecondCalendarUnit ――秒の値
NSWeekCalendarUnit ――週の値(1年の何週目か)
NSWeekdayCalendarUnit ――曜日の値
NSWeekdayOrdinalCalendarUnit ――週の値(今月の何週目か)
NSQuarterCalendarUnit ――第何四半期か
NSCalendarUnit unit = NSYearCalendarUnit|NSMonthCalendarUnit;これで年月の値が取り出せるようになります。――こうして得られるのは、「NSDateComponents」というクラスのインスタすです。これはさまざまな日時の要素を管理するためのもので、メソッドを呼び出して必要な要素の値を取り出すことができます。用意されているメソッドは以下の通りです。
NSInteger 変数 = [《NSDateComponents*》 era];では、下にカレンダーを使って今日の日時から年月日の値をNSDateComponentsで取り出し、出力するサンプルをあげておきましょう。NSCalendarにNSCalendarUnit、NSDateComponentsと新しいクラスやデータタイプがいくつも登場したのでわかりにくいでしょうが、それぞれの役割と基本的な使い方さえ頭に入れれば、そう大変なものではありません。
NSInteger 変数 = [《NSDateComponents*》 year];
NSInteger 変数 = [《NSDateComponents*》 month];
NSInteger 変数 = [《NSDateComponents*》 day];
NSInteger 変数 = [《NSDateComponents*》 hour];
NSInteger 変数 = [《NSDateComponents*》 minute];
NSInteger 変数 = [《NSDateComponents*》 second];
NSInteger 変数 = [《NSDateComponents*》 week];
NSInteger 変数 = [《NSDateComponents*》 weekday];
NSInteger 変数 = [《NSDateComponents*》 weekdayOrdinal];
NSInteger 変数 = [《NSDateComponents*》 quarter];
※リストが表示されない場合
AddBlockなどの広告ブロックツールがONになっているとリストなどが表示されない場合があります。これらのツールをOFFにしてみてください。
#import <Foundation/Foundation.h> int main (int argc, const char * argv[]) { @autoreleasepool { NSDate* date = [NSDate date]; NSCalendar* calendar = [NSCalendar currentCalendar]; NSCalendarUnit unit = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit; NSDateComponents* dc = [calendar components:unit fromDate:date]; NSLog(@"%ld-%ld-%ld",[dc year],[dc month],[dc day]); } return 0; }
<< 前へ | 次へ >> |