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

你可能感兴趣的:(ios时间工具类)