初期化
NSDate *aDate = [NSDate date];
NSLog(@"date: %@", aDate);
特定の日時で初期化
NSDate *aDate2 = [NSDate dateWithString:@"2000-10-24 11:30:00 +0900"];
NSLog(@"date: %@", aDate2);
グレゴリー暦を基にする実現オブジェクト
NSDateComponents *components = [[NSDateComponents alloc] init];
components.year = 1983;
components.month = 1;
//NSCalender カレンダ操作を受け持つオブジェクト
NSCalendar *gregorian
= [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDate *aDate = [gregorian dateFromComponents:components];
//NSDate,descriptionWithLocale:
NSLog(@"My birthday: %@", [aDate descriptionWithLocale:[NSLocale currentLocale]]);
和暦ででも初期化できます
NSDateComponents *component = [[NSDateComponents alloc] init];
component.year = 26; //平成
component.month = 1;
component.day = 2;
component.hour = 18;
component.minute = 38;
component.second = 47;
component.timeZone = [NSTimeZone timeZoneWithName:@"JST"];
NSCalendar *japanese
= [[NSCalendar alloc] initWithCalendarIdentifier:NSJapaneseCalendar];
NSDate *aDate = [japanese dateFromComponents:component];
NSLog(@"今日: %@", aDate);
}
操作
日本語表記
NSLog(@"date: %@", [aDate descriptionWithLocale:[NSLocale currentLocale]]);
加算、減算
NSDate *aDate = [NSDate date];
NSDate *yesterday = [aDate dateByAddingTimeInterval:-60*60*24];
NSLog(@"yesterday: %@", yesterday);
NSDate *tomorrow = [aDate dateByAddingTimeInterval:+60*60*24];
NSLog(@"tomorrow: %@", tomorrow);
日時コンポーネントの取得
NSDate *aDate = [NSDate date];
NSCalendar *gregorian
= [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *components = [gregorian components:(
NSYearCalendarUnit
| NSMonthCalendarUnit
| NSDayCalendarUnit
| NSHourCalendarUnit
| NSMinuteCalendarUnit
| NSSecondCalendarUnit
)
fromDate:aDate];
NSInteger era = components.year;
NSInteger mnt = components.month;
NSInteger day = components.day;
NSInteger hrs = components.hour;
NSInteger min = components.minute;
NSInteger sec = components.second;
NSLog(@"day = %ld, hour = %ld, minute = %ld, second = %ld", day, hrs, min, sec);
NSLog(@"day with components: %04ld-%02ld-%02ld %02ld:%02ld:%02ld",
era,
mnt,
day,
hrs,
min,
sec);
}
文字列表現を取得
NSDate *aDate = [NSDate date];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
formatter.dateStyle = NSDateFormatterFullStyle;
formatter.timeStyle = NSDateFormatterShortStyle;
NSLog(@"date formatted in Japanese: %@", [formatter stringFromDate:aDate]);