自定义时间格式

PSDateFormatter.h

 

#import <Foundation/Foundation.h>

@interface PSDateFormatter : NSObject {
    NSDateFormatter *todayFT;
    NSDateFormatter *thisWeekFT;
    NSDateFormatter *aWeekAgoFT;
}

- (NSString *) getDateDesSinceNow:(NSDate *) date;

+ (id) getInstance;

@end

 

PSDateFormatter.m

 

#import "PSDateFormatter.h"

static PSDateFormatter *instance = nil;

@implementation PSDateFormatter

- (id) init {
    todayFT = [[NSDateFormatter alloc] init];
    [todayFT setDateFormat:@"a h:mm"];
    thisWeekFT = [[NSDateFormatter alloc] init];
    [thisWeekFT setDateFormat:@"EEE"];
    aWeekAgoFT = [[NSDateFormatter alloc] init];
    [aWeekAgoFT setDateFormat:@"yy-M-d"];
    
    return self;
}

+ (id) getInstance {
    if (instance == nil) {
        instance = [[PSDateFormatter alloc] init];
    }
    return instance;
}

- (NSString *) getDateDesSinceNow:(NSDate *) date {
    NSDate *now = [NSDate date];
    NSCalendar *cal = [NSCalendar currentCalendar];
    [cal setTimeZone:[NSTimeZone localTimeZone]];
    NSDateComponents *begin = [cal components:NSYearCalendarUnit | NSMonthCalendarUnit |  NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit| NSSecondCalendarUnit fromDate:now];
    [begin setHour:0];
    [begin setMinute:0];
    [begin setSecond:0];
    NSDate *dayBegin = [cal dateFromComponents:begin];
    
    NSTimeInterval space = [now timeIntervalSinceDate:dayBegin];
    
    NSTimeInterval spDate = -[date timeIntervalSinceNow];
    
    NSString *str;
    if (spDate < space) {
        str = [todayFT stringFromDate:date];
    } else {
        spDate -= space;
        NSTimeInterval oneDay = 86400;
        if (spDate <= oneDay) {
            str = @"昨天";
        } else if (spDate > oneDay && spDate < 6 * oneDay) {
            str = [thisWeekFT stringFromDate:date];
        } else {
            str = [aWeekAgoFT stringFromDate:date];
        }
    }
    
    return str;
}

@end

你可能感兴趣的:(ios,iPhone)