时间与NSString转换

//传进来时间字符串转换

+ (NSString *) getChatTimeString:(NSString *)timeString {

    if (timeString==nil || timeString.length==0 || [timeString isEqualToString:@"0"]||timeString.length < 10) {

#warning XXX

        return @"";

    }

/**将字符串转换成时间*/

    NSDate *timeDate = [CommonFunction getCurrentStringAsDate:timeString];

    NSTimeInterval secondsPerDay = 24 * 60 * 60;

    NSDate *date = [NSDate date];

    NSDate *qian = [date dateByAddingTimeInterval: - 2 * secondsPerDay];

    NSDate *yesterday = [date dateByAddingTimeInterval: -secondsPerDay];

    

    NSString * todayString = [[date description] substringToIndex:10];

    NSString * yesterdayString = [[yesterday description] substringToIndex:10];

    NSString * qianString = [[qian description] substringToIndex:10];

    NSString * dateString = [[timeDate description] substringToIndex:10];

    

    NSString *year1 = [todayString substringWithRange:NSMakeRange(0, 4)];

    NSString *year2 = [timeString substringWithRange:NSMakeRange(0, 4)];

    if ([dateString isEqualToString:todayString]&& timeString.length>=16)//是否等于今天

    {

//        return [timeString substringWithRange:NSMakeRange(11, 5)];

        return [NSString stringWithFormat:@"今天 %@",[timeString substringWithRange:NSMakeRange(11, 5)]];

    } else if ([dateString isEqualToString:yesterdayString])//是否等于昨天

    {

        return [NSString stringWithFormat:@"昨天 %@",[timeString substringWithRange:NSMakeRange(11, 5)]];

    }else if ([dateString isEqualToString:qianString])//是否等于前天

    {

        return [NSString stringWithFormat:@"前天 %@",[timeString substringWithRange:NSMakeRange(11, 5)]];

    }

    else

    {

        if (![year1 isEqualToString:year2]) {

            return timeString;

        }

        return [timeString substringWithRange: NSMakeRange(5, 11)];

    }

//系统时间转换 

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

     NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];

    [dateFormatter setDateFormat: @"YYYY-MM-dd HH:mm"];

    NSDate *dateString = [dateFormatter dateFromString:date];

    return dateString;

}

//获取当前时间日期,返回字符串

+ (NSString *) getCurrentDateAsString {

     NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];

    [dateFormatter setDateFormat: @"YYYY-MM-dd HH:mm:ss"];

    NSString *dateString = [dateFormatter stringFromDate: [NSDate date]];

    return dateString;

}

posted @ 2015-11-20 16:53  TheYouth  阅读(237)  评论(0编辑  收藏  举报