来自NSDate的时间/日期与iOS中的消息和邮件应用程序一样显示

时间:2014-01-20 18:42:47

标签: ios cocoa-touch nsdate

我正在构建一个应用程序,要求我显示时间和日期,如果对象是在24小时之前创建的等等。就像iOS中的消息和邮件应用程序将显示24小时的时间而不是更改它显示天“星期一,星期二......”。我正在寻找是否能找到任何与此完全相同的框架,或者我是否必须为此编写代码?

7 个答案:

答案 0 :(得分:3)

我也需要这个,所以我编写了以下NSDate扩展名:

extension NSDate {

    func formattedRelativeString() -> String {
        let dateFormatter = NSDateFormatter()
        dateFormatter.doesRelativeDateFormatting = true

        if isToday() {
            dateFormatter.timeStyle = .ShortStyle
            dateFormatter.dateStyle = .NoStyle
        } else if isYesterday() {
            dateFormatter.timeStyle = .NoStyle
            dateFormatter.dateStyle = .MediumStyle
        } else if daysAgo() < 6 {
            return dateFormatter.weekdaySymbols[weekday()-1]
        } else {
            dateFormatter.timeStyle = .NoStyle
            dateFormatter.dateStyle = .ShortStyle
        }

        return dateFormatter.stringFromDate(self)
    }
}

这需要Matthew York的优秀chat才能工作。

答案 1 :(得分:2)

Swift 3版@avf响应:

extension NSDate {
    func formattedRelativeString() -> String 
    {
        let dateFormatter = DateFormatter()
        dateFormatter.doesRelativeDateFormatting = true

        if isToday() {
            dateFormatter.timeStyle = .short
            dateFormatter.dateStyle = .none
        } else if isYesterday() {
            dateFormatter.timeStyle = .none
            dateFormatter.dateStyle = .medium
        } else if daysAgo() < 6 {
            return dateFormatter.weekdaySymbols[weekday()-1]
        } else {
            dateFormatter.timeStyle = .none
            dateFormatter.dateStyle = .short
        }

        return dateFormatter.string(from: self as Date)
    }
}

答案 2 :(得分:1)

更新为swift 4:

 extension NSDate {

    func formattedRelativeString() -> String 
    {
        let dateFormatter = DateFormatter()

        if isInToday || isInYesterday {
            /// today and yesterday
            /// Today, 3:57 PM
            dateFormatter.doesRelativeDateFormatting = true
            dateFormatter.timeStyle = .short
            dateFormatter.dateStyle = .short
        } else if isLessThanAweekAgo {

            /// less than a week ago
            /// Friday, 4:03 PM
            dateFormatter.dateFormat = "EEEE, h:mm a"
         } else if isInThisYear {

            // more than a week ago
            // Fri, 4 Aug, 3:55
            dateFormatter.dateFormat = "E, d MMM, h:mm a"
         } else {
            // more than a year ago
            // Aug 10, 2016, 3:56
            dateFormatter.dateFormat = "MMM d, yyyy, h:mm a"
         }

        return dateFormatter.string(from: self)
    }

}

你可以在游乐场测试这些样本日期:

let now = Date()
let yesterday = Date(timeInterval: -24*60*60, since: Date())
let weekAgo = Date(timeInterval: -7*24*60*60, since: Date())
let yearAgo = Date(timeInterval: -366*24*60*60, since: Date())

答案 3 :(得分:1)

以下是使用Swift 4进行本地操作的方法:

extension Date {

    func formatRelativeString() -> String {
        let dateFormatter = DateFormatter()
        let calendar = Calendar(identifier: .gregorian)
        dateFormatter.doesRelativeDateFormatting = true

        if calendar.isDateInToday(self) {
            dateFormatter.timeStyle = .short
            dateFormatter.dateStyle = .none
        } else if calendar.isDateInYesterday(self){
            dateFormatter.timeStyle = .none
            dateFormatter.dateStyle = .medium
        } else if calendar.compare(Date(), to: self, toGranularity: .weekOfYear) == .orderedSame {
            let weekday = calendar.dateComponents([.weekday], from: self).weekday ?? 0
            return dateFormatter.weekdaySymbols[weekday-1]
        } else {
            dateFormatter.timeStyle = .none
            dateFormatter.dateStyle = .short
        }

        return dateFormatter.string(from: self)
    }
}

答案 4 :(得分:0)

NSString *dateString = [NSDateFormatter localizedStringFromDate:[NSDate date]
                                                              dateStyle:NSDateFormatterShortStyle
                                                              timeStyle:NSDateFormatterFullStyle];
        NSLog(@"%@",dateString);

尝试使用此代码,根据您的要求进行修改。

答案 5 :(得分:0)

目标C格式的日期和时间。

使用Matthew York出色的DateTools方法。

NSDate扩展名:

-(NSString *)formatDateTimeToString{
    NSDateFormatter* dateFormatter = [[NSDateFormatter alloc]init];
    [dateFormatter setLocale: [[NSLocale alloc] initWithLocaleIdentifier: [[NSLocale currentLocale] localeIdentifier]]];

    if ([[NSCalendar currentCalendar] isDateInToday:self])
    {
        [dateFormatter setTimeStyle:NSDateFormatterShortStyle];
        [dateFormatter setDateStyle:NSDateFormatterNoStyle];
    }
    else if ([[NSCalendar currentCalendar] isDateInYesterday:self])
    {
        [dateFormatter setDoesRelativeDateFormatting:YES];
        [dateFormatter setTimeStyle:NSDateFormatterNoStyle];
        [dateFormatter setDateStyle:NSDateFormatterMediumStyle];
    }
    else if ([self daysAgo]<6)
    {
        [dateFormatter setDateFormat:@"EEEE"];
    }
    else
    {
        [dateFormatter setTimeStyle:NSDateFormatterNoStyle];
        [dateFormatter setDateStyle:NSDateFormatterShortStyle];
    }
    return  [dateFormatter stringFromDate:self];
}


-(NSInteger)daysAgo{
    return [self daysEarlierThan:[NSDate date]];
}

-(NSInteger)daysEarlierThan:(NSDate *)date{
    return ABS(MIN([self daysFrom:date], 0));
}
-(NSInteger)daysFrom:(NSDate *)date{
    return [self daysFrom:date calendar:nil];
}
-(NSInteger)daysFrom:(NSDate *)date calendar:(NSCalendar *)calendar{
    NSDate *earliest = [self earlierDate:date];
    NSDate *latest = (earliest == self) ? date : self;
    NSInteger multiplier = (earliest == self) ? -1 : 1;
    NSDateComponents *components = [[NSCalendar currentCalendar] components:NSCalendarUnitDay fromDate:earliest toDate:latest options:0];
    return multiplier*components.day;
}

答案 6 :(得分:-1)

使用NSDateFormatter并将其doesRelativeDateFormatting属性设置为YES。