10
10

More than 5 years have passed since last update.

今日、昨日なら文字列で「今日」「昨日」と返し、それ以外の日付ならユーザーの日付フォーマットにあわせた文字列の日付を返すソース

Last updated at Posted at 2014-05-01
+ (NSString *)stringDate:(NSDate *)date{
    NSString *strDate = [NSDateFormatter localizedStringFromDate:date dateStyle:NSDateFormatterMediumStyle timeStyle:NSDateFormatterNoStyle];
    NSDate *today = [NSDate date];
    NSString *strToday = [NSDateFormatter localizedStringFromDate:today dateStyle:NSDateFormatterMediumStyle timeStyle:NSDateFormatterNoStyle];
    if ([strToday isEqualToString:strDate]){
        return NSLocalizedString(@"today", nil);
    }    
    NSCalendar *cal = [NSCalendar currentCalendar];
    NSDateComponents *comps = [[NSDateComponents alloc]init];
    [comps setDay:-1];
    NSDate *yesterday = [cal dateByAddingComponents:comps toDate:today options:0];
    NSString *strYesterday = [NSDateFormatter localizedStringFromDate:yesterday dateStyle:NSDateFormatterMediumStyle timeStyle:NSDateFormatterNoStyle];
    if([strYesterday isEqualToString:strDate]){
        return NSLocalizedString(@"Yesterday", nil);
    }
    return strDate;
}

今日や昨日(場合によっては明日等)は、日付の文字列(例 2014/01/01)を返すよりも、今日や昨日と返した方がユーザーにはわかりやすい場合があるので、そんなとき用に。

10
10
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
10
10