时间字符串以及时间戳解析

Posted 照顾一下

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了时间字符串以及时间戳解析相关的知识,希望对你有一定的参考价值。

项目中用到了许多需要处理时间的地方,专门写了一个类来进行处理。多年之后当我再次看到这个东西时希望我可以微笑面对。

  首先是.h文件

#import <Foundation/Foundation.h>

#import "ALUserDetailAccount.h"

#import "ALLMFTiXianListModel.h"

 @interface LMFAnalysisTime : NSObject

#pragma mark --将时间转换成星期

+ (NSString *)changeTimeStringToWeekWith:(NSString *)time;

#pragma mark --将时间转换成时分

+ (NSString *)changeTimeStringToHMWith:(NSString *)time;

 

#pragma mark --根据日期判断是星期几

+ (NSString *)weekdayStringFromDate:(NSString *)time;

 

#pragma mark --判断给定日期的下一天

+ (NSString *)nextDayTimeStringWith:(NSString *)time;

 

#pragma mark --判断是不是一周内

+ (BOOL)ifDateInAweekToNow:(NSString *)time;

 #pragma mark --判断是不是从当前时间开始的一周内,今天不行

+ (BOOL)ifDateInAweekFromTomorrow:(NSString *)time;

#pragma mark --判断日期是否是从今天开始今天或今天以后的日期

+ (BOOL)ifDateIsAfterToday:(NSString *)time containToday:(BOOL)flag;

#pragma mark --判断是第几月

+ (NSString *)monthStringWith:(NSString *)time;

#pragma mark --返回某一种状态下某个时间段的数据

+ (NSArray *)dataWithState:(NSString *)state andTime:(NSString *)time;

#pragma mark --判断刷新请求的数据是否已经存在了

+ (BOOL)ifDateExistInArray:(NSArray *)array andTimeString:(NSString *)time;

 #pragma mark --判断一维数组中数据是否已经存在

+ (BOOL)ifDateExistInOneArray:(NSArray *)array andTimeString:(NSString *)time;

 

#pragma mark --判断日期是否是今天或者昨天

+ (BOOL)iFDateIsTodayOrYesterdayWith:(NSString *)time;

#pragma mark --判断日期是否是今天

+ (BOOL)ifDateIsToday:(NSString *)time;

 #pragma mark --计算年龄

+ (NSString *)changeBirthdayStringToAge:(NSString *)time;

#pragma mark --判断往期数据是否存在了

+ (BOOL)ifExerciseDataInArray:(NSArray *)array andMid:(NSString *)mid;

+ (BOOL)ifExercisePhotoIsExistInArray:(NSArray *)array andExerciseDate:(NSString *)date;

+ (BOOL)ifTogetherExercisePhotoIsExistInArray:(NSArray *)array andExerciseDate:(NSString *)date;

+ (BOOL)ifKnowledgeHasRead:(NSString *)mid; 

#pragma mark --将设置的时间转化为闹钟的秒数

+ (NSArray *)changeTimeToSeconds:(NSArray *)timeArray;

#pragma mark --判断银行卡是否重复了

+ (BOOL)ifCardHasExist:(NSArray *)array and:(ALLMFTiXianListModel *)model;

#pragma mark --判断日期是当天的第几天,当天为第一天

+ (NSInteger)indexOfDateFromToday:(NSString *)time;

#pragma mark --将日期转化为星座

+ (NSString *)changeDateToConstellation:(NSString *)time;

#pragma mark --将日期转化为月日

+ (NSString *)changeDateToMonthAndDay:(NSString *)time;

@end

  下面是.m文件

#import "LMFAnalysisTime.h"

#import "YRDateFormater.h"

#import "ALExerciseAllCellModel.h"

#import "ALLMFExerciseTogetherPhotosModel.h"

@class LMFAnalysisTime;

 

@implementation LMFAnalysisTime

 

#pragma mark --将时间转换成星期

+ (NSString *)changeTimeStringToWeekWith:(NSString *)time

{

    NSString *week;

    YRDateFormater *endt = [[YRDateFormater alloc] init];

    NSString *nowTime = [endt dateToStringYMD:[NSDate date]];

    //第一步,判断是不是同一天2016-03-20  2016-03-21

    NSString *temp = [time substringToIndex:10];

    if ([temp isEqualToString:nowTime])

    {

        week = @"今天";

        return week;

    }

    else

    {

        NSString *tomorrow = [LMFAnalysisTime nextDayTimeStringWith:time];

        if ([[tomorrow substringToIndex:10] isEqualToString:nowTime])

        {

            week = @"昨天";

        }

        else

        {

            week = [LMFAnalysisTime weekdayStringFromDate:time];

        }

    }

    return week;

}

#pragma mark --将时间转换成时分

+ (NSString *)changeTimeStringToHMWith:(NSString *)time

{

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

    /*

    NSString *monthAndDay;

    YRDateFormater *endt = [[YRDateFormater alloc] init];

    NSString *nowTime = [endt dateToStringYMD:[NSDate date]];

    

    //第一步,判断是不是同一天2016-03-20 00:00:00 2016-03-21

    NSString *temp = [time substringToIndex:10];

    if ([temp isEqualToString:nowTime])

    {

        monthAndDay = [time substringWithRange:NSMakeRange(11, 5)];

        return monthAndDay;

    }

    else

    {

        NSString *tomorrow = [LMFAnalysisTime nextDayTimeStringWith:time];

        if ([tomorrow isEqualToString:nowTime])

        {

            //如果是昨天

            monthAndDay = [time substringWithRange:NSMakeRange(11, 5)];

        }

        else

        {

            //不是昨天

            monthAndDay = [time substringWithRange:NSMakeRange(5, 5)];

        }

    }

    return monthAndDay;

     */

}

 

+ (NSString *)nextDayTimeStringWith:(NSString *)time

{

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

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

    NSDate *inputDate = [formatter dateFromString:time];

    NSDate *tomorrow = [NSDate dateWithTimeInterval:60 * 60 * 24 sinceDate:inputDate];

    NSString *tomorrowTime = [formatter stringFromDate:tomorrow];

    return tomorrowTime;

}

 

+ (NSString*)weekdayStringFromDate:(NSString *)time {

    //判断是否是今天或者昨天

    if ([LMFAnalysisTime iFDateIsTodayOrYesterdayWith:time])

    {

        NSArray *weekdays = [NSArray arrayWithObjects: [NSNull null], @"周日", @"周一", @"周二", @"周三", @"周四", @"周五", @"周六", nil];

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

        NSTimeZone *timeZone = [[NSTimeZone alloc] initWithName:@"Asia/Shanghai"];

        [calendar setTimeZone: timeZone];

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

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

        NSDate *inputDate = [formatter dateFromString:time];

        NSCalendarUnit calendarUnit = NSWeekdayCalendarUnit;

        NSDateComponents *theComponents = [calendar components:calendarUnit fromDate:inputDate];

        return [weekdays objectAtIndex:theComponents.weekday];

    }

    else

    {

        return [time substringWithRange:NSMakeRange(5, 5)];

    }

}

 

+ (BOOL)ifDateInAweekToNow:(NSString *)time

{

    //获取当前时间YYYY-MM-dd

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

    NSString *nowTime = [formatter dateToStringYMD:[NSDate date]];

    for (int i=0; i<7; i++)

    {

        //通过判断从给定时间的第几天是不是今天来判断一周以内

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

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

        NSDate *inputDate = [formatter dateFromString:time];

        NSDate *tomorrow = [NSDate dateWithTimeInterval:i * 60 * 60 * 24 sinceDate:inputDate];

        NSString *tomorrowTime = [formatter stringFromDate:tomorrow];

        NSString *temp = [tomorrowTime substringToIndex:10];

//        NSLog(@"%@-------%@----", temp, time);

        if ([temp isEqualToString:nowTime])

        {

            return YES;

        }

    }

    return NO;

}

 

+ (BOOL)ifDateInAweekFromTomorrow:(NSString *)time

{

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

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

    NSString *tomorrow = [formatter stringFromDate:[NSDate dateWithTimeInterval:60*60*24 sinceDate:[NSDate date]]];

    for (int i=0; i<6; i++)

    {

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

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

        NSDate *inputDate = [formatter dateFromString:tomorrow];

        NSDate *tomorrow1 = [NSDate dateWithTimeInterval:i * 60 * 60 * 24 sinceDate:inputDate];

        NSString *tomorrowTime1 = [formatter stringFromDate:tomorrow1];

        NSString *temp = [tomorrowTime1 substringToIndex:10];

        NSLog(@"----%@-------%@-----", time, temp);

        if ([temp isEqualToString:time])

        {

            return YES;

        }

    }

    return NO;

}

 

#pragma mark --判断日期是否是从今天开始今天或今天以后的日期

+ (BOOL)ifDateIsAfterToday:(NSString *)time containToday:(BOOL)flag

{

    /*today YYYY:mm:dd  

     time YYYY:mm:dd HH:mm:ss

     */

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

    NSString *todayDate = [formatter dateToStringYMD:[NSDate date]];

//    NSLog(@"the date of today is : %@", todayDate);

    NSInteger nowY = [[todayDate substringToIndex:4] integerValue];

    NSInteger nowM = [[todayDate substringWithRange:NSMakeRange(5, 2)] integerValue];

    NSInteger nowD = [[todayDate substringWithRange:NSMakeRange(8, 2)] integerValue];

    

    NSInteger timeY = [[time substringToIndex:4] integerValue];

    NSInteger timeM = [[time substringWithRange:NSMakeRange(5, 2)] integerValue];

    NSInteger timeD = [[time substringWithRange:NSMakeRange(8, 2)] integerValue];

//    NSLog(@"year:%li month:%li day:%li", nowY, nowM, nowD);

//    NSLog(@"year:%li month:%li day:%li", timeY, timeM, timeD);

    if (timeY < nowY)

    {

        return NO;

    }

    else

    {

        if (timeY == nowY)

        {

            if (timeM < nowM)

            {

                return NO;

            }

            else

            {

                if (timeM == nowM)

                {

                    if (flag)

                    {

                        if (timeD < nowD)

                        {

                            return NO;

                        }

                        return YES;

                    }

                    else

                    {

                        if (timeD <= nowD)

                        {

                            return NO;

                        }

                        return YES;

                    }

 

                }

                else

                {

                    return YES;

                }

            }

        }

        else

            return YES;

    }

}

 

+ (NSString *)monthStringWith:(NSString *)time

{

    NSString *month;

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

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

    NSString *nowTime = [formatter stringFromDate:[NSDate date]];

    if ([[time substringToIndex:4] isEqualToString:[nowTime substringToIndex:4]])

    {

        if ([[time substringWithRange:NSMakeRange(5, 2)] isEqualToString:[nowTime substringWithRange:NSMakeRange(5, 2)]])

        {

            month = @"本月";

        }

        else

        {

            month = [NSString stringWithFormat:@"%@月", [time substringWithRange:NSMakeRange(5, 2)]];

        }

    }

    else

    {

        month = @"更早";

    }

    return month;

}

 

+ (NSArray *)dataWithState:(NSString *)state andTime:(NSString *)time

{

    NSMutableArray *dataArray = [NSMutableArray array];

    

    return dataArray;

}

 

+ (BOOL)ifDateExistInArray:(NSArray *)array andTimeString:(NSString *)time

{

    BOOL flag = NO;

    //二维

    for (NSArray *smallArray in array)

    {

        if ([smallArray isKindOfClass:[NSArray class]])

        {

            for (ALUserDetailAccount *model in smallArray)

            {

                if ([[model mid] isEqualToString:time])

                {

                    return YES;

                }

            }

        }

    }

    return flag;

}

 

+ (BOOL)ifDateExistInOneArray:(NSArray *)array andTimeString:(NSString *)time

{

    for (ALUserDetailAccount *model in array)

    {

        if ([[model mid] isEqualToString:time])

        {

            return YES;

        }

    }

    return NO;

}

 

+ (BOOL)iFDateIsTodayOrYesterdayWith:(NSString *)time

{

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

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

    NSString *nowTime = [formatter stringFromDate:[NSDate date]];

    if ([[time substringToIndex:10] isEqualToString:[nowTime substringToIndex:10]])

    {

        return YES;

    }

    else

    {

        //是否是昨天

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

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

        NSDate *inputDate = [formatter dateFromString:time];

        NSDate *tomorrow = [NSDate dateWithTimeInterval:-1 * 60 * 60 * 24 sinceDate:inputDate];

        NSString *tomorrowTime = [formatter stringFromDate:tomorrow];

        NSString *temp = [tomorrowTime substringToIndex:10];

        if ([temp isEqualToString:[nowTime substringToIndex:10]])

        {

            return YES;

        }

        else

        {

            return NO;

        }

    }

}

 

+ (BOOL)ifDateIsToday:(NSString *)time

{

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

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

    NSString *nowTime = [formatter stringFromDate:[NSDate date]];

    if ([[time substringToIndex:10] isEqualToString:[nowTime substringToIndex:10]])

    {

        return YES;

    }

    return NO;

}

 

+ (NSString *)changeBirthdayStringToAge:(NSString *)time

{

    NSString *ageStr;

    if ([time length] < 10)

    {

        return @"0岁";

    }

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

    NSString *nowTime = [formatter dateToStringYMD:[NSDate date]];

    NSString *birthday = [time substringToIndex:10];

    NSInteger nowYear = [[nowTime substringToIndex:4] integerValue];

    NSInteger nowMonth = [[nowTime substringWithRange:NSMakeRange(5, 2)] integerValue];

    NSInteger nowDay = [[nowTime substringFromIndex:8] integerValue];

    NSInteger birthdayYear = [[birthday substringToIndex:4] integerValue];

    NSInteger birthdayMonth = [[birthday substringWithRange:NSMakeRange(5, 2)] integerValue];

    NSInteger birthdayDay = [[birthday substringFromIndex:8] integerValue];

    NSInteger age = nowYear - birthdayYear - 1;

    if (nowMonth > birthdayMonth)

    {

        age++;

    }

    else if (nowMonth == birthdayMonth)

    {

        if (nowDay >= birthdayDay)

        {

            age++;

        }

    }

    ageStr = [NSString stringWithFormat:@"%li岁 ", age];

    return ageStr;

}

 

+ (BOOL)ifExerciseDataInArray:(NSArray *)array andMid:(NSString *)mid

{

    if ([array count])

    {

        for (ALExerciseAllCellModel *obj in array)

        {

            if ([obj.mid isEqualToString:mid])

            {

                return YES;

            }

        }

    }

    return NO;

}

 

+ (BOOL)ifExercisePhotoIsExistInArray:(NSArray *)array andExerciseDate:(NSString *)date

{

    if ([array count])

    {

        for (ALLMFExercisePhotosModel *model in array)

        {

            if ([model.exerciseTime isEqualToString:date])

            {

                return YES;

            }

        }

    }

    return NO;

}

 

+ (BOOL)ifTogetherExercisePhotoIsExistInArray:(NSArray *)array andExerciseDate:(NSString *)date

{

    if ([array count])

    {

        for (ALLMFExerciseTogetherPhotosModel *model in array)

        {

            if ([model.exerciseTime isEqualToString:date])

            {

                return YES;

            }

        }

    }

    return NO;

}

 

+ (NSArray *)changeTimeToSeconds:(NSArray *)timeArray

{

    NSMutableArray *secondsArray = [NSMutableArray array];

    for (NSString *time in timeArray)

    {

        NSString *currentTime;

        if ([time length] == 5)

        {

            currentTime = [NSString stringWithFormat:@"%@:00", time];

        }

        else

        {

            currentTime = [NSString stringWithFormat:@"0%@:00", time];

        }

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

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

        NSString *nowTime = [[[judgeFormatter stringFromDate:[NSDate date]] substringFromIndex:11] stringByReplacingOccurrencesOfString:@" " withString:@""];

        NSInteger currentHour = [[currentTime substringToIndex:2] integerValue];

        NSInteger currentMinute = [[currentTime substringWithRange:NSMakeRange(3, 2)] integerValue];

        NSInteger currenSecond = 0;

        

        NSInteger nowHour = [[nowTime substringToIndex:2] integerValue];

        NSInteger nowMinute = [[nowTime substringWithRange:NSMakeRange(3, 2)] integerValue];

        NSInteger nowSecond = [[nowTime substringFromIndex:6] integerValue];

        

        NSInteger timeCha;

        NSInteger hourCha = currentHour - nowHour;

        NSInteger minuteCha = currentMinute - nowMinute;

        NSInteger secondCha = currenSecond - nowSecond;

        timeCha = hourCha*3600+minuteCha*60+secondCha;

        NSLog(@"%li", timeCha);

        [secondsArray addObject:[NSString stringWithFormat:@"%li", timeCha]];

    }

    return secondsArray;

}

 

+ (BOOL)ifCardHasExist:(NSArray *)array and:(ALLMFTiXianListModel *)model

{

    if ([array count])

    {

        for (int i=0; i<[array count]; i++)

        {

            ALLMFTiXianListModel *obj = [[array objectAtIndex:i] objectAtIndex:0];

            if ([obj.cardNo isEqualToString:model.cardNo])

            {

                return YES;

            }

        }

        return NO;

    }

    else

    {

        return NO;

    }

}

 

+ (NSInteger)indexOfDateFromToday:(NSString *)time

{

    NSInteger index;

    /*获取当前日期*/

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

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

    NSDate *date = [NSDate date];

    /*将传入的时间拼接成标注格式的日期*/

    NSString *currentTime = time;

    if ([time length] < 19)

    {

        currentTime = [NSString stringWithFormat:@"%@ 00:00:00", time];

    }

    for (NSInteger i=0; i<10; i++)

    {

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

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

        NSDate *tomorrow = [NSDate dateWithTimeInterval:-i * 60 * 60 * 24 sinceDate:date];

        NSString *tomorrowTime = [formatter stringFromDate:tomorrow];

        NSString *temp = [tomorrowTime substringToIndex:10];

        index = i+1;

        if ([temp isEqualToString:time])

        {

            return index;

        }

    }

    return 11;

}

 

+ (BOOL)ifKnowledgeHasRead:(NSString *)mid

{

    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];

    NSString *userId = [userDefaults objectForKey:@"userId"];

    NSString *key = [NSString stringWithFormat:@"%@_hasRead", userId];

    NSMutableArray *dicArray = [NSMutableArray array];

    dicArray = [[[ALCacheService shareCacheService] getDictionaryForKey:key tableName:@"knowledgeTable"] objectForKey:@"hasRead"];

    if ([dicArray count])

    {

        for (NSDictionary *dic in dicArray)

        {

            if ([mid isEqualToString:[dic objectForKey:@"hasRead"]])

            {

                return YES;

            }

        }

        return NO;

    }

    else

    {

        return NO;

    }

    return NO;

}

 

+ (NSString *)changeDateToConstellation:(NSString *)time

{

    NSString *constellation = @"猎户座";

    NSInteger index = 0;

    NSArray *constellationArray = @[@"魔蝎座", @"水瓶座" ,@"双鱼座" ,@"白羊座" ,@"金牛座" ,@"双子座" ,@"巨蟹座" ,@"狮子座", @"处女座", @"天秤座", @"天蝎座", @"射手座"];

    /*12.22-1.19  1.20-2.18  2.19-3.20  3.21-4.19  4.20-5.20  5.21-6.21  6.22-7.22  7.23-8.22  8.23-9.22 9.23-10.23 10.24-11.22 11.23-12.21*/

    NSDictionary *dic = @{@"12":@"22", @"1":@"20", @"2":@"19", @"3":@"21", @"4":@"20", @"5":@"21", @"6":@"22", @"7":@"23", @"8":@"23", @"9":@"23", @"10":@"24", @"11":@"23"};

    /*

     2016-10-10 00:00:00

     规则是:首先将时间分割成月和日

     通过月找到对应的日,判断日期是否大于临界点,大则加1

     */

    NSString *month = @"3";

    NSInteger day;

    if ([time length] >= 10)

    {

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

        month = [NSString stringWithFormat:@"%li", [monthStr integerValue]];

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

    }

    else if ([time length] == 4 || [time length] == 5)

    {

        NSRange range;

        if ([time contains:@"-"])

        {

            range = [time rangeOfString:@"-"];

        }

        else if ([time contains:@"."])

        {

            range = [time rangeOfString:@"."];

        }

        else

        {

            range = NSMakeRange(0, 0);

        }

        if (range.length && range.location != NSNotFound)

        {

            NSString *monthStr = [time substringToIndex:range.location];

            month = [NSString stringWithFormat:@"%li", [monthStr integerValue]];

            day = [[time substringFromIndex:range.location+1] integerValue];

        }

        else

        {

            return constellation;

        }

    }

    else

    {

        return constellation;

    }

    index = [month integerValue]%12;

    NSInteger temp = [[dic objectForKey:month] integerValue];

    if (day < temp)

    {

        index--;

        if (index < 0)

        {

            index = 11;

        }

    }

    return constellationArray[index];

}

 

+ (NSString *)changeDateToMonthAndDay:(NSString *)time

{

    NSString *monthAndDay = @"01月01日";

    if ([time length] >= 10)

    {

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

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

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

    }

    return monthAndDay;

}

@end

  上面有几个文件没有的可以删除,然后删除对应的几个方法。(菜鸟成长之路,望各位大神指教??)

以上是关于时间字符串以及时间戳解析的主要内容,如果未能解决你的问题,请参考以下文章

time/datetime

如何解析类型“时间戳”不是类型转换中“字符串”类型的子类型

日期对象 SimpleDateFormat 未在 Java(Android)环境中正确解析时间戳字符串

将字符串时间戳解析为即时抛出不受支持的字段:InstantSeconds

Python时间模块之Time模块解析

将时间戳数据解析为本地日期和时间的问题