LoginSignup
6
5

More than 5 years have passed since last update.

~日前表示

Last updated at Posted at 2015-02-04

地味にハマったので残します。和暦に注意。

viewController.m


- (void)viewDidLoad {

    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    [formatter setCalendar:calendar];
    NSDate *date = [formatter dateFromString:@"2015-02-04 00:00:00"];

    UILabel *label = [UILabel alloc]init];
    label.text = [self displayDate:date];

}

- (NSString *)displayDate:(NSDate*)timestamp {

    NSDate *now = [NSDate date];
    NSTimeInterval passed = [now timeIntervalSinceDate:timestamp];
    int min = passed / 60;
    if (min <= 1) {
        return @"1分前";
    }
    if (min < 60) {
        return [NSString stringWithFormat:@"%d分前", min];
    }
    int hour = min / 60;
    if (hour < 24) {
        return [NSString stringWithFormat:@"%d時間前", hour];
    }
    int day = hour / 24;
    return [NSString stringWithFormat:@"%d日前", day];
}
6
5
2

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
6
5