How to convert NSDate in to relative format as “To

2019-01-06 10:08发布

I want to convert nsdate in to relative format like "Today","Yesterday","a week ago","a month ago","a year ago","date as it is".

I have written following method for it.. but some how its just printing as it is date.. can you please tell me what should be the problem?

//Following is my function which converts the date into relative string

+(NSString *)getDateDiffrence:(NSDate *)strDate{
    NSDateFormatter *df = [[NSDateFormatter alloc] init];

    df.timeStyle = NSDateFormatterMediumStyle;
    df.dateStyle = NSDateFormatterShortStyle;
    df.doesRelativeDateFormatting = YES;
    NSLog(@"STRING DATEEE : %@ REAL DATE TODAY %@",[df stringFromDate:strDate],[NSDate date]);
      return [df stringFromDate:strDate];

}

I have date string with the following format "2013-10-29T09:38:00"

When I tried to give the NSDate object then its always return me null date.
so I tried to convert that date in to yyyy-MM-dd HH:mm:ssZZZZ then I pass this date to function then it's just printing whole date..

How to solve this problem?

//Following is the code I call the above function

NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss"];
NSDate *date = [formatter dateFromString:[threadDict objectForKey:@"lastMessageDate"]];
[formatter setDateFormat:@"yyyy-MM-dd HH:mm:ssZZZZ"];

NSString *date1 = [formatter stringFromDate:date];
NSDate *date_d = [formatter dateFromString:date1];
NSString *resultstr=[UserManager getDateDiffrence:date];

self.dateLabel.text=resultstr;

16条回答
疯言疯语
2楼-- · 2019-01-06 10:36

check NSDate-TimeAgo, it also supports multiple languages.

查看更多
孤傲高冷的网名
3楼-- · 2019-01-06 10:36

To format the given "sourceDate" as "5:56 pm" for today, "yesterday" for any time yesterday, "January 16" for any day in the same year and "January 16, 2014". I am posting my own method.

sourceDate = //some date that you need to take into consideration


 NSDateComponents *components = [[NSCalendar currentCalendar] components:NSCalendarUnitMinute | NSCalendarUnitHour | NSCalendarUnitDay | NSCalendarUnitMonth | NSCalendarUnitYear fromDate:[NSDate date]];
    NSDateComponents *sourceDateComponents = [[NSCalendar currentCalendar] components:NSCalendarUnitMinute | NSCalendarUnitHour | NSCalendarUnitDay | NSCalendarUnitMonth | NSCalendarUnitYear fromDate: sourceDate];

    NSString* timestamp;

    NSDateFormatter *formatSourceDate   =   [NSDateFormatter new];
    [formatSourceDate setAMSymbol:@"AM"];
    [formatSourceDate setPMSymbol:@"PM"];

    //same day - time in h:mm am/pm
    if (components.day == sourceDateComponents.day) {
        NSLogInfo(@"time");
        [formatSourceDate setDateFormat:@"h:mm a"];
        timestamp = [NSString stringWithFormat:@"%@",[formatSourceDate stringFromDate:date]];
        return timestamp;
    }
    else if (components.day - sourceDateComponents.day == 1) {
        //yesterday
        timestamp = NSLocalizedString(@"Yesterday", nil);
        return timestamp;
    }
    if (components.year == sourceDateComponents.year) {
        //september 29, 5:56 pm
        [formatSourceDate setDateFormat:@"MMMM d"];
        timestamp = [NSString stringWithFormat:@"%@",[formatSourceDate stringFromDate:date]];
        return timestamp;
    }
    [formatSourceDate setDateFormat:@"MMMM d year"];
    timestamp = [NSString stringWithFormat:@"%@",[formatSourceDate stringFromDate:date]];
    return timestamp;

    NSLogInfo(@"Timestamp : %@",timestamp);
查看更多
一夜七次
4楼-- · 2019-01-06 10:37

Here is code I created for my use:

+ (NSString*) getTimestampForDate:(NSDate*)date {

    NSDate* sourceDate = date;

    // Timezone Offset compensation (optional, if your target users are limited to a single time zone.)

    NSTimeZone* sourceTimeZone = [NSTimeZone timeZoneWithName:@"America/New_York"];
    NSTimeZone* destinationTimeZone = [NSTimeZone systemTimeZone];

    NSInteger sourceGMTOffset = [sourceTimeZone secondsFromGMTForDate:sourceDate];
    NSInteger destinationGMTOffset = [destinationTimeZone secondsFromGMTForDate:sourceDate];

    NSTimeInterval interval = destinationGMTOffset - sourceGMTOffset;

    NSDate* destinationDate = [[NSDate alloc] initWithTimeInterval:interval sinceDate:sourceDate];

    // Timestamp calculation (based on compensation)

    NSCalendar* currentCalendar = [NSCalendar currentCalendar];
    NSCalendarUnit unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit |  NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit;

    NSDateComponents *differenceComponents = [currentCalendar components:unitFlags fromDate:destinationDate toDate:[NSDate date] options:0];//Use `date` instead of `destinationDate` if you are not using Timezone offset correction

    NSInteger yearDifference = [differenceComponents year];
    NSInteger monthDifference = [differenceComponents month];
    NSInteger dayDifference = [differenceComponents day];
    NSInteger hourDifference = [differenceComponents hour];
    NSInteger minuteDifference = [differenceComponents minute];

    NSString* timestamp;

    if (yearDifference == 0
        && monthDifference == 0
        && dayDifference == 0
        && hourDifference == 0
        && minuteDifference <= 2) {

        //"Just Now"

        timestamp = @"Just Now";

    } else if (yearDifference == 0
               && monthDifference == 0
               && dayDifference == 0
               && hourDifference == 0
               && minuteDifference < 60) {

        //"13 minutes ago"

        timestamp = [NSString stringWithFormat:@"%ld minutes ago", (long)minuteDifference];

    } else if (yearDifference == 0
               && monthDifference == 0
               && dayDifference == 0
               && hourDifference == 1) {

        //"1 hour ago" EXACT

        timestamp = @"1 hour ago";

    } else if (yearDifference == 0
               && monthDifference == 0
               && dayDifference == 0
               && hourDifference < 24) {

        timestamp = [NSString stringWithFormat:@"%ld hours ago", (long)hourDifference];

    } else {

        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        [formatter setLocale:[NSLocale currentLocale]];

        NSString* strDate, *strDate2 = @"";

        if (yearDifference == 0
            && monthDifference == 0
            && dayDifference == 1) {

            //"Yesterday at 10:23 AM", "Yesterday at 5:08 PM"

            [formatter setDateFormat:@"hh:mm a"];
            strDate = [formatter stringFromDate:date];

            timestamp = [NSString stringWithFormat:@"Yesterday at %@", strDate];

        } else if (yearDifference == 0
                   && monthDifference == 0
                   && dayDifference < 7) {

            //"Tuesday at 7:13 PM"

            [formatter setDateFormat:@"EEEE"];
            strDate = [formatter stringFromDate:date];
            [formatter setDateFormat:@"hh:mm a"];
            strDate2 = [formatter stringFromDate:date];

            timestamp = [NSString stringWithFormat:@"%@ at %@", strDate, strDate2];

        } else if (yearDifference == 0) {

            //"July 4 at 7:36 AM"

            [formatter setDateFormat:@"MMMM d"];
            strDate = [formatter stringFromDate:date];
            [formatter setDateFormat:@"hh:mm a"];
            strDate2 = [formatter stringFromDate:date];

            timestamp = [NSString stringWithFormat:@"%@ at %@", strDate, strDate2];

        } else {

            //"March 24 2010 at 4:50 AM"

            [formatter setDateFormat:@"d MMMM yyyy"];
            strDate = [formatter stringFromDate:date];
            [formatter setDateFormat:@"hh:mm a"];
            strDate2 = [formatter stringFromDate:date];

            timestamp = [NSString stringWithFormat:@"%@ at %@", strDate, strDate2];
        }
    }

    return timestamp;
}
查看更多
趁早两清
5楼-- · 2019-01-06 10:38

Here's my answer (in Swift 3!) and why it's better.

Answer:

func datePhraseRelativeToToday(from date: Date) -> String {

    // Don't use the current date/time. Use the end of the current day 
    // (technically 0h00 the next day). Apple's calculation of 
    // doesRelativeDateFormatting niavely depends on this start date.
    guard let todayEnd = dateEndOfToday() else {
        return ""
    }

    let calendar = Calendar.autoupdatingCurrent

    let units = Set([Calendar.Component.year,
                 Calendar.Component.month,
                 Calendar.Component.weekOfMonth,
                 Calendar.Component.day])

    let difference = calendar.dateComponents(units, from: date, to: todayEnd)

    guard let year = difference.year,
        let month = difference.month,
        let week = difference.weekOfMonth,
        let day = difference.day else {
            return ""
    }

    let timeAgo = NSLocalizedString("%@ ago", comment: "x days ago")

    let dateFormatter: DateFormatter = {
        let formatter = DateFormatter()
        formatter.locale = Locale.autoupdatingCurrent
        formatter.dateStyle = .medium
        formatter.doesRelativeDateFormatting = true
        return formatter
    }()

    if year > 0 {
        // sample output: "Jan 23, 2014"
        return dateFormatter.string(from: date)
    } else if month > 0 {
        let formatter = DateComponentsFormatter()
        formatter.unitsStyle = .brief // sample output: "1mth"
        formatter.allowedUnits = .month
        guard let timePhrase = formatter.string(from: difference) else {
            return ""
        }
        return String(format: timeAgo, timePhrase)
    } else if week > 0 {
        let formatter = DateComponentsFormatter()
        formatter.unitsStyle = .brief; // sample output: "2wks"
        formatter.allowedUnits = .weekOfMonth
        guard let timePhrase = formatter.string(from: difference) else {
            return ""
        }
        return String(format: timeAgo, timePhrase)
    } else if day > 1 {
            let formatter = DateComponentsFormatter()
            formatter.unitsStyle = .abbreviated; // sample output: "3d"
            formatter.allowedUnits = .day
            guard let timePhrase = formatter.string(from: difference) else {
                return ""
            }
            return String(format: timeAgo, timePhrase)
    } else {
        // sample output: "Yesterday" or "Today"
        return dateFormatter.string(from: date)
    }
}

func dateEndOfToday() -> Date? {
    let calendar = Calendar.autoupdatingCurrent
    let now = Date()
    let todayStart = calendar.startOfDay(for: now)
    var components = DateComponents()
    components.day = 1
    let todayEnd = calendar.date(byAdding: components, to: todayStart)
    return todayEnd
}

Remember to reuse your formatters to avoid any performance hit! Hint: extensions on DateFormatter and DateComponentsFormatter are good ideas.

Why it's better:

  • Utilizes DateFormatter's "Yesterday" and "Today". This is already translated by Apple, which saves you work!
  • Uses DateComponentsFormatter's already translated "1 week" string. (Again less work for you, courtesy of Apple.) All you have to do is translate the "%@ ago" string.
查看更多
等我变得足够好
6楼-- · 2019-01-06 10:39

I have attached demo here please find on this link. TimestampAgo-Demo

Thanks to n00bprogrammer

Edit :- I made changes in Sourcetimezone with [NSTimeZone systemTimeZone] because due to static time zone , issue occure in GMT or UTC format. (second goes in minus) and change deprecated Methods.

查看更多
小情绪 Triste *
7楼-- · 2019-01-06 10:42

Here is my solution in Swift 2 that avoid 24-hour problem by comparing two dates with a zero time.

extension NSDate {

private func dateWithZeroTime(date: NSDate) -> NSDate? {
    let calendar = NSCalendar.currentCalendar()
    let units: NSCalendarUnit = [.Day, .WeekOfYear, .Month, .Year]
    let components = calendar.components(units, fromDate: date)
    return calendar.dateFromComponents(components)
}

private func thisDay() -> NSDate? {
    return self.dateWithZeroTime(self)
}

private func today() -> NSDate? {
    return self.dateWithZeroTime(NSDate())
}

var relativeFormat: String? {
    let today = self.today()
    let thisDay = self.thisDay()

    let formatter = NSDateFormatter()
    formatter.dateStyle = NSDateFormatterStyle.LongStyle
    let dateString = formatter.stringFromDate(self)

    if nil != thisDay && nil != today {
        let units: NSCalendarUnit = [.Day, .WeekOfYear, .Month, .Year]
        let components = NSCalendar.currentCalendar().components(units, fromDate: thisDay!, toDate: today!, options: [])

        if (components.year > 0) {
            return components.year == 1 ? "A year ago, \(dateString)" : "\(components.year) years ago, \(dateString)"
        } else if (components.month > 0) {
            return components.month == 1 ? "A month ago, \(dateString)" : "\(components.month) months ago, \(dateString)"
        } else if (components.weekOfYear > 0) {
            return components.weekOfYear == 1 ? "A week ago, \(dateString)" : "\(components.weekOfYear) weeks ago, \(dateString)"
        } else if (components.day > 0) {
            return components.day == 1 ? "Yesterday, \(dateString)" : "\(self.dayOfTheWeek()), \(dateString)"
        } else {
            return "Today"
        }
    }

    return nil
}

func dayOfTheWeek() -> String {
    let weekdays = [
        "Sunday",
        "Monday",
        "Tuesday",
        "Wednesday",
        "Thursday",
        "Friday",
        "Saturday"
    ]

    let calendar: NSCalendar = NSCalendar.currentCalendar()
    let components: NSDateComponents = calendar.components(.Weekday, fromDate: self)
    return weekdays[components.weekday - 1]
}
}
查看更多
登录 后发表回答