ios时间工具类

//

//  TimeUtil.h

//  wq

//

//  Created by berwin on 13-7-20.

//  Copyright (c) 2013年 Weqia. All rights reserved.

//

#import

@interface TimeUtil : NSObject

+ (NSString*)getTimeStr:(long) createdAt;

///获取年月日 时分秒  // 格式:  2020-09-04 13:50:55

+ (NSString*)getFullTimeStr:(longlong)time;

///获取年月日  时分  // 格式:  2020-09-04 13:50

+ (NSString*)getFullTimeStrNoSecond:(long long)time;

///获取年月日  // 格式:  2020.09.04

+ (NSString*)getFullTimeStr1:(long long)time;

///获取年月日  // 格式:  2020-09-04

+ (NSString*)getFullTimeStr2:(long long)time;

///获取天,时分秒  // 格式: 02:13:50:55

+ (NSString*)getDayHourMinuteSecondStr:(long long)time;

///获取 时分秒    // 格式: 13:50:55

+ (NSString*)getHourMinuteSecondStr:(long long)time;

///获取月日  09月28日

+ (NSString*)getMDStr:(longlong)time;

///获取月日 09.28

+ (NSString*)getMDStr1:(longlong)time;

///获取年

+ (NSString*)getYearStr:(longlong)timeformat:(NSString*)format;

///获取月

+ (NSString*)getMonthStr:(longlong)timeformat:(NSString*)format;

///获取日

+ (NSString*)getDayStr:(longlong)timeformat:(NSString*)format;

///获取星期

+ (NSString*)getWeekdayStr:(longlong)timeformat:(NSString*)format;

+(NSDateComponents*) getComponent:(long long)time;

/// 朋友圈时间格式 例:6天前

/// @param time 时间戳

+(NSString*) getTimeStrStyle1:(long long)time;

+(NSString*) getTimeStrStyle2:(long long)time;

+(NSString*) getTimeStrStyle3:(long long)time;

/// dataFormat

+ (NSString*)getDate:(NSDate*)datewithFormat:(NSString*)dataFormat;

+ (NSDate*)getDateWithDateString:(NSString*)date dateFormat:(NSString*)format;

// 默认格式时间,聊天用

+ (NSString*)getDefaultDateFormat:(NSDate*)date;

// 获取消息列表时间格式

+ (NSString*)getMessageDateFormat:(NSDate*)date;

// 聊天时间格式

+ (NSString*)getChatDateFormat:(NSDate*)date;

// 获取朋友圈时间格式

+ (NSString*)getFriendsCircleDateFormat:(NSDate*)date;

//

+ (NSString*)getTimeStrStyle4:(NSDate *)date;

/**

 *  2016.03.11转时间戳

 *

 *  @param time 时间

 *

 *  @return 时间戳

 */

+ (longlong)getTimestamp:(NSString*)time;

//将NSDate类型的时间转换为时间戳(秒),从1970/1/1开始

+(long long)getDateTimeTOSeconds:(NSDate *)datetime;

//将NSDate类型的时间转换为时间戳字符串(秒),从1970/1/1开始

+(NSString *)getDateTimeTOSecondStr:(NSDate *)datetime;

//将NSDate类型的时间转换为时间戳(毫秒),从1970/1/1开始

+(long long)getDateTimeTOMilliSeconds:(NSDate *)datetime;

//将NSDate类型的时间转换为时间戳字符串(毫秒),从1970/1/1开始

+(NSString *)getDateTimeTOMilliSecondStr:(NSDate *)datetime;

/// 获取当前时间戳(秒)  格式: 1596685586

+(NSString *)getNowTimeTimestamp;

/// 获取当前时间戳(毫秒)  格式: 1596685586000

+(NSString *)getNowTimeMilliSecondTimestamp;

/// 获取当前时间戳(秒)  格式: 1596685586

+(long)getNowTime;

/// 获取当前时间戳(毫秒)  格式: 1596685586000

+(long)getNowTimeMilliSecond;

/// 获取零点时间戳  格式: 1596685586

+(long)getTodayZreoTime;

/// 获取24点时间戳(秒)  格式: 1596685586

+(long)getToday24OclockTime;

/// 获取当前时间  格式: 2019-2-14 10:00:30

+(NSString *)getCurrentTimes;

/// 根据结束时间来获取剩余倒计时格式化时间  格式: 10:00:30

+(NSString *)getHourMinuteSecondCountDownToEndTime:(long)endTime;

/// 根据结束时间来获取剩余倒计时格式化时间  格式: 10:10:00:30

+(NSString *)getDayHourMinuteSecondCountDownToEndTime:(long)endTime;

/// 根据结束时间来获取剩余倒计时格式化时间  格式: 10天10时00分30秒

+(NSString *)getDayHourMinuteSecondCountDownToEndTime2:(long)endTime;

/// 根据指定时间来获取目标天数 格式: 10天

+(NSString*)getDayToEndTime:(long)startTime;

// 获取现在时间到N年后的时间

+(NSString*)getNyearsTime:(long)year;

// 获取指定时间到N年后的时间

+(NSString *)getTargetYearToNyearsTime:(long)targetTime nYears:(long)nYears;

// 传入秒数  得到 xx时xx分

+(NSString*)getMMSSFromSS:(long)totalTime;

@end

//

//  TimeUtil.m

//  wq

//

//  Created by berwin on 13-7-20.

//  Copyright (c) 2013年 Weqia. All rights reserved.

//

#import "TimeUtil.h"

@implementation TimeUtil

+ (NSString*)getTimeStr:(long) createdAt

{

    // Calculate distance time string

    //

    NSString*timestamp;

    time_tnow;

    time(&now);


    intdistance = (int)difftime(now, createdAt);

    if(distance <0) distance =0;


    if(distance <60) {

        timestamp = [NSStringstringWithFormat:@"%d %s", distance, (distance ==1) ?"second ago":"seconds ago"];

    }

    elseif(distance <60*60) {

        distance = distance /60;

        timestamp = [NSStringstringWithFormat:@"%d %s", distance, (distance ==1) ?"minute ago":"minutes ago"];

    }

    elseif(distance <60*60*24) {

        distance = distance /60/60;

        timestamp = [NSStringstringWithFormat:@"%d %s", distance, (distance ==1) ?"hour ago":"hours ago"];

    }

    elseif(distance <60*60*24*7) {

        distance = distance /60/60/24;

        timestamp = [NSString stringWithFormat:@"%d %s", distance, (distance ==1) ?"day ago":"days ago"];

    }

    elseif(distance <60*60*24*7*4) {

        distance = distance /60/60/24/7;

        timestamp = [NSString stringWithFormat:@"%d %s", distance, (distance ==1) ?"week ago":"weeks ago"];

    }

    else{

        staticNSDateFormatter *dateFormatter =nil;

        if(dateFormatter ==nil) {

            dateFormatter = [[NSDateFormatter alloc] init];

            [dateFormatter setDateStyle:NSDateFormatterShortStyle];

            [dateFormatter setTimeStyle:NSDateFormatterShortStyle];

        }


        NSDate *date = [NSDate dateWithTimeIntervalSince1970:createdAt]; 

        timestamp = [dateFormatter stringFromDate:date];

    }

    returntimestamp;

}

+ (NSString*)getFullTimeStr:(longlong)time

{

    NSDate * date=[NSDate dateWithTimeIntervalSince1970:time];

    NSCalendar * calendar=[[NSCalendar alloc]initWithCalendarIdentifier:NSCalendarIdentifierGregorian];

    NSInteger unitFlags = NSCalendarUnitMonth | NSCalendarUnitDay|NSCalendarUnitYear|NSCalendarUnitHour|NSCalendarUnitMinute|NSCalendarUnitSecond;

    NSDateComponents * component=[calendar components:unitFlags fromDate:date];

    NSString * string=[NSString stringWithFormat:@"%04zd-%02zd-%02zd %02zd:%02zd:%02zd",[component year],[component month],[component day],[component hour],[component minute],[component second]];

    returnstring;

}

+ (NSString*)getDayHourMinuteSecondStr:(long long)time

{

    NSDate * date=[NSDate dateWithTimeIntervalSince1970:time];

    NSCalendar * calendar=[[NSCalendar alloc]initWithCalendarIdentifier:NSCalendarIdentifierGregorian];

    NSInteger unitFlags = NSCalendarUnitMonth | NSCalendarUnitDay|NSCalendarUnitYear|NSCalendarUnitHour|NSCalendarUnitMinute|NSCalendarUnitSecond;

    NSDateComponents * component=[calendar components:unitFlags fromDate:date];

    NSString * string=[NSString stringWithFormat:@"%02zd:%02zd:%02zd:%02zd",[component day],[component hour],[component minute],[component second]];

    returnstring;

}

+ (NSString*)getHourMinuteSecondStr:(long long)time

{

    NSDate * date=[NSDate dateWithTimeIntervalSince1970:time];

    NSCalendar * calendar=[[NSCalendar alloc]initWithCalendarIdentifier:NSCalendarIdentifierGregorian];

    NSInteger unitFlags = NSCalendarUnitMonth | NSCalendarUnitDay|NSCalendarUnitYear|NSCalendarUnitHour|NSCalendarUnitMinute|NSCalendarUnitSecond;

    NSDateComponents * component=[calendar components:unitFlags fromDate:date];

    NSString * string=[NSString stringWithFormat:@"%02zd:%02zd:%02zd",[component hour],[component minute],[component second]];

    returnstring;

}

+ (NSString*)getFullTimeStrNoSecond:(long long)time

{

    NSDate * date=[NSDate dateWithTimeIntervalSince1970:time];

    NSCalendar * calendar=[[NSCalendar alloc]initWithCalendarIdentifier:NSCalendarIdentifierGregorian];

    NSInteger unitFlags = NSCalendarUnitMonth | NSCalendarUnitDay|NSCalendarUnitYear|NSCalendarUnitHour|NSCalendarUnitMinute|NSCalendarUnitSecond;

    NSDateComponents * component=[calendar components:unitFlags fromDate:date];

    NSString * string=[NSString stringWithFormat:@"%04zd-%02zd-%02zd %02zd:%02zd",[component year],[component month],[component day],[component hour],[component minute]];

    returnstring;

}

+ (NSString*)getFullTimeStr1:(longlong)time

{

    NSDate * date=[NSDate dateWithTimeIntervalSince1970:time];

    NSCalendar * calendar=[[NSCalendar alloc]initWithCalendarIdentifier:NSCalendarIdentifierGregorian];

    NSInteger unitFlags = NSCalendarUnitMonth | NSCalendarUnitDay|NSCalendarUnitYear|NSCalendarUnitHour|NSCalendarUnitMinute|NSCalendarUnitSecond;

    NSDateComponents * component=[calendar components:unitFlags fromDate:date];

    NSString * string=[NSString stringWithFormat:@"%04zd.%02zd.%02zd ",[component year],[component month],[component day]];

    returnstring;

}

+ (NSString*)getFullTimeStr2:(longlong)time

{

    NSDate * date=[NSDate dateWithTimeIntervalSince1970:time];

    NSCalendar * calendar=[[NSCalendar alloc]initWithCalendarIdentifier:NSCalendarIdentifierGregorian];

    NSInteger unitFlags = NSCalendarUnitMonth | NSCalendarUnitDay|NSCalendarUnitYear|NSCalendarUnitHour|NSCalendarUnitMinute|NSCalendarUnitSecond;

    NSDateComponents * component=[calendar components:unitFlags fromDate:date];

    NSString * string=[NSString stringWithFormat:@"%04zd-%02zd-%02zd ",[component year],[component month],[component day]];

    returnstring;

}

+ (NSString*)getMDStr:(longlong)time

{


    NSDate * date=[NSDate dateWithTimeIntervalSince1970:time];

    NSCalendar * calendar=[[NSCalendar alloc]initWithCalendarIdentifier:NSCalendarIdentifierGregorian];

    NSInteger unitFlags = NSCalendarUnitMonth | NSCalendarUnitDay|NSCalendarUnitYear|NSCalendarUnitHour|NSCalendarUnitMinute|NSCalendarUnitSecond;

    NSDateComponents * component=[calendar components:unitFlags fromDate:date];

    NSString * string=[NSString stringWithFormat:@"%.2zd月%.2zd日",[component month],[component day]];

    returnstring;

}

+ (NSString*)getMDStr1:(longlong)time

{


    NSDate * date=[NSDate dateWithTimeIntervalSince1970:time];

    NSCalendar * calendar=[[NSCalendar alloc]initWithCalendarIdentifier:NSCalendarIdentifierGregorian];

    NSInteger unitFlags = NSCalendarUnitMonth | NSCalendarUnitDay|NSCalendarUnitYear|NSCalendarUnitHour|NSCalendarUnitMinute|NSCalendarUnitSecond;

    NSDateComponents * component=[calendar components:unitFlags fromDate:date];

    NSString * string=[NSString stringWithFormat:@"%.2zd-%.2zd",[component month],[component day]];

    returnstring;

}

+ (NSString*)getMonthStr:(longlong)timeformat:(NSString *)format

{


    NSDate * date=[NSDate dateWithTimeIntervalSince1970:time];

    NSCalendar * calendar=[[NSCalendar alloc]initWithCalendarIdentifier:NSCalendarIdentifierGregorian];

    NSInteger unitFlags = NSCalendarUnitMonth | NSCalendarUnitDay|NSCalendarUnitYear|NSCalendarUnitHour|NSCalendarUnitMinute|NSCalendarUnitSecond;

    NSDateComponents * component=[calendar components:unitFlags fromDate:date];

    NSString * string =nil;

    if(format ==nil) {

        string=[NSString stringWithFormat:@"%.2zd",[component month]];

    }else{

        string=[NSString stringWithFormat:@"%.2zd%@",[component month],format];

    }

    returnstring;

}

+ (NSString*)getYearStr:(longlong)timeformat:(NSString *)format

{

    NSDate * date=[NSDate dateWithTimeIntervalSince1970:time];

    NSCalendar * calendar=[[NSCalendar alloc]initWithCalendarIdentifier:NSCalendarIdentifierGregorian];

    NSInteger unitFlags = NSCalendarUnitMonth | NSCalendarUnitDay|NSCalendarUnitYear|NSCalendarUnitHour|NSCalendarUnitMinute|NSCalendarUnitSecond;

    NSDateComponents * component=[calendar components:unitFlags fromDate:date];

    NSString * string =nil;

    if(format ==nil) {

         string = [NSString stringWithFormat:@"%04zd",[component year]];

    }else{

         string = [NSString stringWithFormat:@"%04zd%@",[component year],format];

    }

    returnstring;

}

+ (NSString*)getDayStr:(longlong)timeformat:(NSString *)format

{


    NSDate * date=[NSDate dateWithTimeIntervalSince1970:time];

    NSCalendar * calendar=[[NSCalendar alloc]initWithCalendarIdentifier:NSCalendarIdentifierGregorian];

    NSInteger unitFlags = NSCalendarUnitMonth | NSCalendarUnitDay|NSCalendarUnitYear|NSCalendarUnitHour|NSCalendarUnitMinute|NSCalendarUnitSecond;

    NSDateComponents * component=[calendar components:unitFlags fromDate:date];


    NSString * string =nil;

    if(format ==nil) {

        string=[NSString stringWithFormat:@"%zd",[component day]];

    }else{

        string=[NSString stringWithFormat:@"%zd%@",[component day],format];

    }

    returnstring;

}

+ (NSString*)getWeekdayStr:(longlong)timeformat:(NSString *)format{

    NSDate * date=[NSDate dateWithTimeIntervalSince1970:time];

    NSCalendar * calendar=[[NSCalendar alloc]initWithCalendarIdentifier:NSCalendarIdentifierGregorian];

    NSInteger unitFlags = NSCalendarUnitMonth | NSCalendarUnitDay|NSCalendarUnitYear|NSCalendarUnitHour|NSCalendarUnitMinute|NSCalendarUnitSecond|NSCalendarUnitWeekOfYear|NSCalendarUnitWeekOfMonth|NSCalendarUnitWeekday;

    NSDateComponents * component=[calendar components:unitFlags fromDate:date];


    NSInteger year=[component year];

    NSInteger week=[component weekOfYear];

    NSInteger weekday=[component weekday];


    NSDate * today=[NSDate date];

    component=[calendar components:unitFlags fromDate:today];


    NSInteger t_year=[component year];

    NSInteger t_week=[component weekOfYear];


    NSString*string=nil;

   if(year==t_year&&week==t_week)

    {

        NSString * daystr=nil;

        switch(weekday) {

            case1:

                daystr=@"日";

                break;

            case2:

                daystr=@"一";

                break;

            case3:

                daystr=@"二";

                break;

            case4:

                daystr=@"三";

                break;

            case5:

                daystr=@"四";

                break;

            case6:

                daystr=@"五";

                break;

            case7:

                daystr=@"六";

                break;

            default:

                break;

        }

        if(format ==nil) {

            string=[NSString stringWithFormat:@"%@",daystr];

        }else{

            string=[NSString stringWithFormat:@"%@%@",format,daystr];

        }

    }

    returnstring;

}

+(NSDateComponents*)getComponent:(longlong)time

{

    NSDate * date=[NSDate dateWithTimeIntervalSince1970:time];

    NSCalendar * calendar=[[NSCalendar alloc]initWithCalendarIdentifier:NSCalendarIdentifierGregorian];

    NSInteger unitFlags = NSCalendarUnitMonth | NSCalendarUnitDay|NSCalendarUnitYear|NSCalendarUnitHour|NSCalendarUnitMinute|NSCalendarUnitSecond;

    NSDateComponents * component=[calendar components:unitFlags fromDate:date];

    returncomponent;

}

+(NSString*)getTimeStrStyle1:(longlong)time

{

    NSDate * date=[NSDate dateWithTimeIntervalSince1970:time];

    NSCalendar * calendar=[[NSCalendar alloc]initWithCalendarIdentifier:NSCalendarIdentifierGregorian];

    NSInteger unitFlags = NSCalendarUnitMonth | NSCalendarUnitDay|NSCalendarUnitYear|NSCalendarUnitHour|NSCalendarUnitMinute|NSCalendarUnitSecond|NSCalendarUnitWeekOfYear|NSCalendarUnitWeekOfMonth|NSCalendarUnitWeekday;

    NSDateComponents * component=[calendar components:unitFlags fromDate:date];

    NSInteger year=[component year];

    NSInteger month=[component month];

    NSInteger day=[component day];


    NSDate * today=[NSDate date];

    component=[calendar components:unitFlags fromDate:today];


    NSInteger t_year=[component year];


    NSString*string=nil;


    longlongnow=[today timeIntervalSince1970];


    longdistance=(long)(now-time);

    if(distance<60)

        string=@"刚刚";

    elseif(distance<60*60)

        string=[NSString stringWithFormat:@"%ld 分钟前",distance/60];

    elseif(distance<60*60*24)

        string=[NSString stringWithFormat:@"%ld 小时前",distance/60/60];

    elseif(distance<60*60*24*7)

        string=[NSString stringWithFormat:@"%ld 天前",distance/60/60/24];

    elseif(year==t_year)

        string=[NSString stringWithFormat:@"%zd月%zd日",month,day];

    else

        string=[NSString stringWithFormat:@"%zd年%zd月%zd日",year,month,day];


    returnstring;   


}

+(NSString*)getTimeStrStyle2:(longlong)time

{

    NSDate * date=[NSDate dateWithTimeIntervalSince1970:time];

    NSCalendar * calendar=[[NSCalendar alloc]initWithCalendarIdentifier:NSCalendarIdentifierGregorian];

    NSInteger unitFlags = NSCalendarUnitMonth | NSCalendarUnitDay|NSCalendarUnitYear|NSCalendarUnitHour|NSCalendarUnitMinute|NSCalendarUnitSecond|NSCalendarUnitWeekOfYear|NSCalendarUnitWeekOfMonth|NSCalendarUnitWeekday;

    NSDateComponents * component=[calendar components:unitFlags fromDate:date];


    NSInteger year=[component year];

    NSInteger month=[component month];

    NSInteger day=[component day];

    NSInteger hour=[component hour];

    NSInteger minute=[component minute];

    NSInteger week=[component weekOfYear];

    NSInteger weekday=[component weekday];


    NSDate * today=[NSDate date];

    component=[calendar components:unitFlags fromDate:today];


    NSInteger t_year=[component year];

    NSInteger t_month=[component month];

    NSInteger t_day=[component day];

    NSInteger t_week=[component weekOfYear];


    NSString*string=nil;

    if(year==t_year&&month==t_month&&day==t_day)

    {

        if(hour<6&&hour>=0)

             string=[NSString stringWithFormat:@"凌晨 %zd:%02zd",hour,minute];

        elseif(hour>=6&&hour<12)

            string=[NSString stringWithFormat:@"上午 %zd:%02zd",hour,minute];

        elseif(hour>=12&&hour<18)

            string=[NSString stringWithFormat:@"下午 %zd:%02zd",hour-12,minute];

        else

            string=[NSString stringWithFormat:@"晚上 %zd:%02zd",hour-12,minute];

    }

    elseif(year==t_year&&week==t_week)

    {

        NSString * daystr=nil;

        switch(weekday) {

            case1:

                daystr=@"日";

                break;

            case2:

                daystr=@"一";

                break;

            case3:

                daystr=@"二";

                break;

            case4:

                daystr=@"三";

                break;

            case5:

                daystr=@"四";

                break;

            case6:

                daystr=@"五";

                break;

            case7:

                daystr=@"六";

                break;

            default:

                break;

        }

        string=[NSString stringWithFormat:@"周%@ %zd:%02zd",daystr,hour,minute];

    }

    elseif(year==t_year)

        string=[NSString stringWithFormat:@"%zd月%zd日",month,day];

    else

        string=[NSString stringWithFormat:@"%zd年%zd月%zd日",year,month,day];


    returnstring;

}

+(NSString*)getTimeStrStyle3:(longlong)time

{

    NSDate * date=[NSDate dateWithTimeIntervalSince1970:time];

    NSCalendar * calendar=[[NSCalendar alloc]initWithCalendarIdentifier:NSCalendarIdentifierGregorian];

    NSInteger unitFlags = NSCalendarUnitMonth | NSCalendarUnitDay|NSCalendarUnitYear|NSCalendarUnitHour|NSCalendarUnitMinute|NSCalendarUnitSecond|NSCalendarUnitWeekOfYear|NSCalendarUnitWeekOfMonth|NSCalendarUnitWeekday;

    NSDateComponents * component=[calendar components:unitFlags fromDate:date];


    NSInteger year=[component year];

    NSInteger month=[component month];

    NSInteger day=[component day];

    NSInteger hour=[component hour];

    NSInteger minute=[component minute];


    NSDate * today=[NSDate date];

    component=[calendar components:unitFlags fromDate:today];


    NSInteger t_year=[component year];

    NSInteger t_month=[component month];

    NSInteger t_day=[component day];


    NSString*string=nil;

    if(year==t_year&&month==t_month&&day==t_day)

    {

        if(hour<6&&hour>=0)

            string=[NSString stringWithFormat:@"凌晨 %zd:%02zd",hour,minute];

        elseif(hour>=6&&hour<12)

            string=[NSString stringWithFormat:@"上午 %zd:%02zd",hour,minute];

        elseif(hour>=12&&hour<18)

            string=[NSString stringWithFormat:@"下午 %zd:%02zd",hour-12,minute];

        else

            string=[NSString stringWithFormat:@"晚上 %zd:%02zd",hour-12,minute];

    }

    elseif(year==t_year)

        string=[NSString stringWithFormat:@"%zd-%zd %zd:%02zd",month,day,hour,minute];

    else

        string=[NSString stringWithFormat:@"%02zd-%zd-%zd %zd:%02zd",year%100,month,day,hour,minute];


    returnstring;

}

#pragma mark- dataFormat

+ (NSString*)getDate:(NSDate*)datewithFormat:(NSString*)dataFormat{

    if(date ==nil) {

        date = [[NSDate alloc] init];

    }

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

    [formatter setDateFormat:dataFormat];

    NSString *theDate = [formatter stringFromDate:date];

    returntheDate;

}

+ (NSDate*)getDateWithDateString:(NSString*)datedateFormat:(NSString*)format{

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

    [dateFormat setDateFormat:format];

    return[dateFormat dateFromString:date];

}

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

    NSDate * today = [NSDate date];

    NSDate * refDate = date;


    NSString * todayString = [[selfgetDate:today withFormat:kDateFormatDefault] substringToIndex:10];

    NSString * refDateString = [[selfgetDate:refDate withFormat:kDateFormatDefault] substringToIndex:10];


    NSString * yearString = [[selfgetDate:today withFormat:kDateFormatDefault] substringToIndex:4];

    NSString * refYearString = [[selfgetDate:refDate withFormat:kDateFormatDefault] substringToIndex:4];


    if([refDateString isEqualToString:todayString])

    {

        return[selfgetDate:date withFormat:kDateFormatTime];

    }elseif([yearString isEqualToString:refYearString]){

        return[selfgetDate:date withFormat:kDateFormat_MdHms];

    }else{

        return[selfgetDate:date withFormat:kDateFormatDefault];

    }

}

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

    NSDate * today = [NSDate date];

    NSDate * refDate = date;


    NSString * todayString = [[selfgetDate:today withFormat:kDateFormatDefault] substringToIndex:10];

    NSString * refDateString = [[selfgetDate:refDate withFormat:kDateFormatDefault] substringToIndex:10];


    NSString * yearString = [[selfgetDate:today withFormat:kDateFormatDefault] substringToIndex:4];

    NSString * refYearString = [[selfgetDate:refDate withFormat:kDateFormatDefault] substringToIndex:4];


    if([refDateString isEqualToString:todayString])

    {

        return[selfgetDate:date withFormat:kDateFormat_Hm];

    }elseif([yearString isEqualToString:refYearString]){

        return[selfgetDate:date withFormat:kDateFormat_Md];

    }else{

        return[selfgetDate:date withFormat:kDateFormat_yyMd];

    }

}

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

    //获取系统是24小时制或者12小时制

    NSString *formatStringForHours = [NSDateFormatter dateFormatFromTemplate:@"j" options:0 locale:[NSLocale currentLocale]];

    NSRangecontainsA = [formatStringForHoursrangeOfString:@"a"];

    BOOLhasAMPM = containsA.location!=NSNotFound;

    //hasAMPM==TURE为12小时制,否则为24小时制

    if(hasAMPM) {

        return [self getTimeStrStyle3:date.timeIntervalSince1970];

    }else{

        NSDate* today = [NSDatedate];

        NSDate* refDate = date;


        NSString* todayString = [[selfgetDate:todaywithFormat:kDateFormatDefault]substringToIndex:10];

        NSString* refDateString = [[selfgetDate:refDatewithFormat:kDateFormatDefault]substringToIndex:10];


        NSString* yearString = [[selfgetDate:todaywithFormat:kDateFormatDefault]substringToIndex:4];

        NSString* refYearString = [[selfgetDate:refDatewithFormat:kDateFormatDefault]substringToIndex:4];


        if([refDateStringisEqualToString:todayString])

        {

            return[selfgetDate:datewithFormat:kDateFormat_Hm];

        }elseif([yearStringisEqualToString:refYearString]){

            return[selfgetDate:datewithFormat:kDateFormat_MdHm];

        }else{

            return[selfgetDate:datewithFormat:kDateFormat_yyMdHm];

        }

    }

}

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

    NSDate* today = [NSDatedate];

    NSDate* refDate = date;


    NSString* todayString = [[selfgetDate:todaywithFormat:kDateFormatDefault]substringToIndex:10];

    NSString* refDateString = [[selfgetDate:refDatewithFormat:kDateFormatDefault]substringToIndex:10];


    NSString* yearString = [[selfgetDate:todaywithFormat:kDateFormatDefault]substringToIndex:4];

    NSString* refYearString = [[selfgetDate:refDatewithFormat:kDateFormatDefault]substringToIndex:4];


    if([refDateStringisEqualToString:todayString])

    {

        return@"今天";

    }elseif([yearStringisEqualToString:refYearString]){

        return[selfgetDate:datewithFormat:kDateFormat_Md];

    }else{

        return[selfgetDate:datewithFormat:kDateFormat_yyMd];

    }

}

+ (NSString*)getTimeStrStyle4:(NSDate *)date

{

    NSCalendar * calendar=[[NSCalendar alloc]initWithCalendarIdentifier:NSCalendarIdentifierGregorian];

    NSInteger unitFlags = NSCalendarUnitMonth | NSCalendarUnitDay|NSCalendarUnitYear|NSCalendarUnitHour|NSCalendarUnitMinute|NSCalendarUnitSecond|NSCalendarUnitWeekOfYear|NSCalendarUnitWeekOfMonth|NSCalendarUnitWeekday;

    NSDateComponents* component=[calendarcomponents:unitFlagsfromDate:date];


    NSIntegeryear=[componentyear];

    NSIntegermonth=[componentmonth];

    NSIntegerday=[componentday];

    NSIntegerhour=[componenthour];

    NSIntegerminute=[componentminute];

    NSIntegerweekday=[componentweekday];


    NSDate* today=[NSDatedate];

    component=[calendarcomponents:unitFlagsfromDate:today];

    NSIntegert_year=[componentyear];

    NSInteger t_month=[component month];

    NSInteger t_day=[component day];



    NSDate * yesterday = [NSDate dateWithTimeIntervalSinceNow:-86400];


    NSString * todayString = [[selfgetDate:date withFormat:kDateFormatDefault] substringToIndex:10];

    NSString * refDateString = [[selfgetDate:yesterday withFormat:kDateFormatDefault] substringToIndex:10];


    NSString *noTimeStr = [selfgetDate:date withFormat:kDateFormat_yMd];

    NSDate *noTime = [selfgetDateWithDateString:noTimeStr dateFormat:kDateFormat_yMd];


    longlongnow=[today timeIntervalSince1970];

    longdistance=(long)(now-[noTime timeIntervalSince1970]);



    NSString*string=[NSString stringWithFormat:@"%zd:%02zd",hour,minute];

    if(year==t_year&&month==t_month&&day==t_day){}

    elseif([todayString isEqualToString:refDateString])

        string=[NSString stringWithFormat:@"昨天 %zd:%02zd",hour,minute];

    elseif(distance<60*60*24*7)

    {

        NSString *daystr;

        switch(weekday) {

            case1:

                daystr=@"日";

                break;

            case2:

                daystr=@"一";

                break;

            case3:

                daystr=@"二";

                break;

            case4:

                daystr=@"三";

                break;

            case5:

                daystr=@"四";

                break;

            case6:

                daystr=@"五";

                break;

            case7:

                daystr=@"六";

                break;

            default:

                break;

        }

        string=[NSString stringWithFormat:@"星期%@ %zd:%02zd",daystr,hour,minute];

    }

    elseif(year==t_year)

        string=[NSString stringWithFormat:@"%zd-%zd %zd:%02zd",month,day,hour,minute];

    else

        string=[NSString stringWithFormat:@"%02zd-%zd-%zd %zd:%02zd",year%100,month,day,hour,minute];


    returnstring;

}

/**

 *  2016.03.11转时间戳

 *

 *  @param time 时间

 *

 *  @return 时间戳

 */

+ (longlong)getTimestamp:(NSString *)time

{

    NSString * year = [time substringWithRange:NSMakeRange(0,4)];

    NSString * moth = [time substringWithRange:NSMakeRange(5,2)];

    NSString * day = [time substringWithRange:NSMakeRange(8,2)];

    NSString *timeStr = [NSString stringWithFormat:@"%@-%@-%@ 00:00:00",year,moth,day];

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

    [formatter setDateStyle:NSDateFormatterMediumStyle];

    [formatter setTimeStyle:NSDateFormatterShortStyle];

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

    NSDate* date = [formatter dateFromString:timeStr];//将字符串按formatter转成nsdate

     longlongtimeSp = [date timeIntervalSince1970];

     returntimeSp;

}

//将NSDate类型的时间转换为时间戳(秒),从1970/1/1开始

+(longlong)getDateTimeTOSeconds:(NSDate *)datetime{

    return[selfgetDateTimeTOMilliSeconds:datetime]/1000.0;

}

//将NSDate类型的时间转换为时间戳字符串(秒),从1970/1/1开始

+(NSString *)getDateTimeTOSecondStr:(NSDate *)datetime{

    return[NSString stringWithFormat:@"%lld",[selfgetDateTimeTOSeconds:datetime]];

}

//将NSDate类型的时间转换为时间戳,从1970/1/1开始

+(long long)getDateTimeTOMilliSeconds:(NSDate *)datetime{


    NSTimeInterval interval = [datetime timeIntervalSince1970];

    longlongtotalMilliseconds = interval*1000;

    returntotalMilliseconds;

}

+(NSString *)getDateTimeTOMilliSecondStr:(NSDate *)datetime{

    return[NSString stringWithFormat:@"%lld",[selfgetDateTimeTOMilliSeconds:datetime]];

}

+(NSString *)getNowTimeTimestamp{

    return[NSString stringWithFormat:@"%ld", [selfgetNowTime]];

}

+(NSString *)getNowTimeMilliSecondTimestamp{

    return[NSString stringWithFormat:@"%ld", [selfgetNowTimeMilliSecond]];

}

/// 获取当前时间戳(秒)  格式: 1596685586

+(long)getNowTime{

    NSDate *datenow = [NSDate date];

    return(long)[datenow timeIntervalSince1970];

}

/// 获取当前时间戳(毫秒)  格式: 1596685586000

+(long)getNowTimeMilliSecond{

    return[selfgetNowTime]*1000;

}

/// 获取零点时间戳  格式: 1596685586

+(long)getTodayZreoTime{


    NSDate *now = [NSDate date];

    NSCalendar *cal = [NSCalendar currentCalendar];

    unsignedintunitFlags = NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitMinute |NSCalendarUnitSecond;

    NSDateComponents *zerocompents = [cal components:unitFlags fromDate:now];

    // 转化成0晨0点时间

    zerocompents.hour =0;

    zerocompents.minute =0;

    zerocompents.second =0;

    // NSdatecomponents转NSdate类型

    NSDate* newdate= [cal dateFromComponents:zerocompents];

    // //时间转时间戳格式(该时间已经是当天凌晨零点的时刻)

    NSTimeInterval zeroInterval = [newdate timeIntervalSince1970];

    return(long)zeroInterval;


}

/// 获取24点时间戳(秒)  格式: 1596685586

+(long)getToday24OclockTime{

    // 计算二十四点时间戳

    longtimeZreoInt = [selfgetTodayZreoTime];

    returntimeZreoInt +86400;

}

+ (NSString *)getCurrentTimes{

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

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

    NSDate *datenow = [NSDate date];

    NSString *currentTimeString = [formatter stringFromDate:datenow];

    returncurrentTimeString;

}

//根据结束时间来获取剩余倒计时格式化时间  格式: 10:00:30

+(NSString *)getHourMinuteSecondCountDownToEndTime:(long)endTime{


    longnowTime = [selfgetNowTime];

    if(nowTime >= endTime) {return@"00:00:00";}

    longsecondsCountDown = endTime - nowTime;

    // 重新计算 时/分/秒

    NSString *hourStr = [NSString stringWithFormat:@"%02ld", secondsCountDown /3600];

    NSString *minuteStr = [NSString stringWithFormat:@"%02ld", (secondsCountDown %3600) /60];

    NSString *secondStr = [NSString stringWithFormat:@"%02ld", secondsCountDown %60];

    NSString *formatTime = [NSString stringWithFormat:@"%@:%@:%@", hourStr, minuteStr, secondStr];

    returnformatTime;


}

//根据结束时间来获取剩余倒计时格式化时间  格式: 10:10:00:30

+(NSString *)getDayHourMinuteSecondCountDownToEndTime:(long)endTime{


    longnowTime = [selfgetNowTime];

    if(nowTime >= endTime) {return@"00:00:00:00";}

    longsecondsCountDown = endTime - nowTime;


    // 重新计算 天/时/分/秒

    longdaySecond =3600*24;

    NSString *dayStr = [NSString stringWithFormat:@"%02ld", secondsCountDown / daySecond];

    NSString *hourStr = [NSString stringWithFormat:@"%02ld", (secondsCountDown % daySecond)/3600];

    NSString *minuteStr = [NSString stringWithFormat:@"%02ld", (secondsCountDown %3600) /60];

    NSString *secondStr = [NSString stringWithFormat:@"%02ld", secondsCountDown %60];

    NSString *formatTime = [NSString stringWithFormat:@"%@:%@:%@:%@", dayStr, hourStr, minuteStr, secondStr];

    returnformatTime;


}

//根据结束时间来获取剩余倒计时格式化时间  格式: 10天10时00分30秒

+ (NSString *)getDayHourMinuteSecondCountDownToEndTime2:(long)endTime {

    longnowTime = [selfgetNowTime];

    if(nowTime >= endTime) {return@"00天00时00分00秒";}

    longsecondsCountDown = endTime - nowTime;


    // 重新计算 天/时/分/秒

    longdaySecond =3600*24;

    NSString *dayStr = [NSString stringWithFormat:@"%02ld", secondsCountDown / daySecond];

    NSString *hourStr = [NSString stringWithFormat:@"%02ld", (secondsCountDown % daySecond)/3600];

    NSString *minuteStr = [NSString stringWithFormat:@"%02ld", (secondsCountDown %3600) /60];

    NSString *secondStr = [NSString stringWithFormat:@"%02ld", secondsCountDown %60];

    NSString *formatTime = [NSString stringWithFormat:@"%@天%@时%@分%@秒", dayStr, hourStr, minuteStr, secondStr];

    returnformatTime;

}

+ (NSString *)getDayToEndTime:(long)startTime {


    longnowTime = [selfgetNowTime];

    if(nowTime <= startTime) {return@"0天";}

    longsecondsCountDown = nowTime - startTime;


    // 重新计算 天

    longdaySecond =3600*24;

    NSString *dayStr = [NSString stringWithFormat:@"%02ld", secondsCountDown / daySecond];

    NSString *formatTime = [NSString stringWithFormat:@"%@天", dayStr];

    returnformatTime;

}

+ (NSString *)getNyearsTime:(long)year {


    longnowTime = [selfgetNowTime];


    longtargetTime =60*60*24*365* year;


    NSString *str = [selfgetFullTimeStr2:targetTime + nowTime];


    returnstr;


}

+ (NSString *)getTargetYearToNyearsTime:(long)targetTimenYears:(long)nYears {


    longtargetTime2 =60*60*24*365* nYears;

    NSString *str = [selfgetFullTimeStr2:targetTime + targetTime2];


    returnstr;


}

+ (NSString *)getMMSSFromSS:(long)totalTime {

    NSString *str_hour = [NSString stringWithFormat:@"%02ld",totalTime/3600];

    NSString *str_minute = [NSString stringWithFormat:@"%02ld",(totalTime%3600)/60];

    NSString *format_time = [NSString stringWithFormat:@"%@时%@分",str_hour,str_minute];


    if([format_time isEqualToString:@"00时00分"]) {

        format_time =@"0分";

    }

    returnformat_time;

}

@end

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 203,772评论 6 477
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 85,458评论 2 381
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 150,610评论 0 337
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,640评论 1 276
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,657评论 5 365
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,590评论 1 281
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,962评论 3 395
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,631评论 0 258
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,870评论 1 297
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,611评论 2 321
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,704评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,386评论 4 319
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,969评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,944评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,179评论 1 260
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 44,742评论 2 349
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,440评论 2 342