NSDate中的时间/日期显示,就像iOS中的消息和邮件应用程序一样

vd2z7a6w  于 2023-08-08  发布在  iOS
关注(0)|答案(8)|浏览(91)

我正在构建一个应用程序,需要我显示时间和日期,即星期日,如果对象是在24小时之前创建等。就像iOS中的消息和邮件应用程序将显示24小时的时间,而不是将其更改为显示“星期一,星期二”这样的日子。我正在寻找,如果我可以找到任何框架,这样做完全一样,或者我必须写一个代码?

du7egjpx

du7egjpx1#

以下是如何在Swift 4和5中原生完成这一切:

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)
    }
}

字符串

avkwfej4

avkwfej42#

我也需要这个,所以我写了下面的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约克出色的DateTools来工作。

flmtquvp

flmtquvp3#

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)
    }
}

字符串

izkcnapc

izkcnapc4#

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)
    }

}

字符串
你可以在playground上用这些样本日期来测试它:

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())

xqkwcwgp

xqkwcwgp5#

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

字符串
试试这个代码,根据你的要求修改它。

rn0zuynd

rn0zuynd6#

目标C格式化日期和时间。
使用Matthew约克优秀的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;
}

字符串

b4wnujal

b4wnujal7#

我尝试了所有的方法,但不幸的是,没有一个对我有效。不管怎样,我最终找到了一个解决方案。

Swift版本

extension Date {

    func isEqual(to date: Date, toGranularity component: Calendar.Component, in calendar: Calendar = .current) -> Bool {
        calendar.isDate(self, equalTo: date, toGranularity: component)
    }

    func isInSameYear(as date: Date) -> Bool { isEqual(to: date, toGranularity: .year) }
    func isInSameMonth(as date: Date) -> Bool { isEqual(to: date, toGranularity: .month) }
    func isInSameWeek(as date: Date) -> Bool { isEqual(to: date, toGranularity: .weekOfYear) }

    func isInSameDay(as date: Date) -> Bool { Calendar.current.isDate(self, inSameDayAs: date) }

    var isInThisYear:  Bool { isInSameYear(as: Date()) }
    var isInThisMonth: Bool { isInSameMonth(as: Date()) }
    var isInThisWeek:  Bool { isInSameWeek(as: Date()) }

    var isInYesterday: Bool { Calendar.current.isDateInYesterday(self) }
    var isInToday:     Bool { Calendar.current.isDateInToday(self) }
    var isInTomorrow:  Bool { Calendar.current.isDateInTomorrow(self) }

    var isInTheFuture: Bool { self > Date() }
    var isInThePast:   Bool { self < Date() }
    
    func formattedRelativeString() -> String {
        let dateFormatter = DateFormatter()
        
        if self.addingTimeInterval(60) > Date() {
            // less than a minute
            return "Now"
        } else if isInToday || isInYesterday {
            // today and yesterday
            // Today, 3:57 PM
            dateFormatter.doesRelativeDateFormatting = true
            dateFormatter.timeStyle = .short
            dateFormatter.dateStyle = .short
        } else if isInThisWeek {
            // 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 AM
            dateFormatter.dateFormat = "E, d MMM, h:mm a"
        } else {
            // more than a year ago
            // 10 Aug, 2016, 3:56 AM
            dateFormatter.dateFormat = "d MMM, yyyy, h:mm a"
        }
            
        return dateFormatter.string(from: self)
    }
}

字符串
您可以根据需要更改每个日期的格式。要创建自己的自定义日期格式,请参阅此article

输出

let now = Date().formattedRelativeString()
//  Now

let today = Date(timeInterval: -60*60, since: Date()).formattedRelativeString()
//  Today, 9:06 AM

let yesterday = Date(timeInterval: -24*60*60, since: Date()).formattedRelativeString()
//  Yesterday, 10:06 AM

let weekAgo = Date(timeInterval: -7*24*60*60, since: Date()).formattedRelativeString()
//  Fri, 28 Jul, 10:06 AM

let yearAgo = Date(timeInterval: -366*24*60*60, since: Date()).formattedRelativeString()
//  3 Aug, 2022, 10:06 AM

hjzp0vay

hjzp0vay8#

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

相关问题