LoginSignup
2
2

More than 5 years have passed since last update.

NSDate関連のメモ

Last updated at Posted at 2013-12-31
NSDate
    NSDate *now = [NSDate date];

    // ロケールを指定する.
    NSLocale *locale = [NSLocale currentLocale];
    NSLog(@"now[%@]", [now descriptionWithLocale:locale]);

    // NSDateFormatterオブジェクトの生成.
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setLocale:[NSLocale systemLocale]];
    [formatter setTimeZone:[NSTimeZone systemTimeZone]];

    // 日付から文字列への変換.
    [formatter setDateFormat:@"yyyy年MM月dd日 HH時mm分ss秒"];
    NSString *strDate = [formatter stringFromDate:now];
    NSLog(@"now2[%@]", strDate);

    // 文字列から日付への変換.
    [formatter setDateFormat:@"yyyy/MM/dd HH:mm:ss"];
    NSDate *oneDay = [formatter dateFromString:@"2013/12/12 23:59:59"];
    NSLog(@"now3[%@", [oneDay descriptionWithLocale:locale]);

    // 東京五輪までの日数.
    NSDate *tokyoOlympic = [formatter dateFromString:@"2020/07/24 20:00:00"];
    NSTimeInterval secs = [tokyoOlympic timeIntervalSinceDate:now];
    NSInteger dayes = round(secs/(60*60*24));
    NSLog(@"あと%d日", dayes);

    // 数値を指定してNSDateを取得する.
    NSDateComponents *components = [[NSDateComponents alloc] init];
    components.year = 2014;
    components.month = 1;
    components.day = 28;
    components.hour = 23;
    NSCalendar *cal = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    date = [cal dateFromComponents:components];
    NSLog(@"date: %@", date);
    NSLog(@"date: %@", [date descriptionWithLocale:[NSLocale currentLocale]]);

    // NSDateから数値を取得する.
    components = [cal components:(NSDayCalendarUnit|NSHourCalendarUnit|NSSecondCalendarUnit) fromDate:date];
    NSInteger day = components.day;
    NSInteger hour = components.hour;
    NSInteger sec = components.second;
    NSLog(@"day=%ld hour=%ld sec=%ld", day, hour, sec);

2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2