不在赘述理论,直接贴代码
typedef enum : NSUInteger {
Date1BelongToPast = -1,
Date1BelongToToday = 0,
Date1BelongToFeature = 1,
} Date1BelongTo;
@interface DateViewCtrl()
@end
@implementation DateViewCtrl
-(void)viewDidLoad{
[super viewDidLoad];
NSDate *currDate = [NSDate date];
/**
1.NSDate实例/类 的基础使用
*/
[self basicisHandleOfNSDateInstanceOrClass];
/**
2.判断NSDate对应的是星期几
*/
NSString *currWeekdayStr = [self weekdayStringFromDate:currDate];
DLog(@”currWeekdayStr:%@”,currWeekdayStr);
/**
3.获取NSDate实例对应的是年月日
*/
NSString *currDateInChineseCalendar = [self getChineseCalendarWithDate:currDate];
DLog(@”currDateInChineseCalendar:%@”,currDateInChineseCalendar);
/**
4.字符串转化成NSDate类型 计算与当前时间的相差 月数 天数
这个方法是将两个时间计算时间差处理
*/
[self computeDateWithTodayWithDateStr:@”2016-12-1 11:23:23″];
[self computeDateWithTodayWithDateStr:@”2016-11-30 11:23:23″];
[self computeDateWithTodayWithDateStr:@”2012-05-17 11:23:23″];
/**
5.将秒转化为天,时,分,秒
*/
NSString *timeDurationdecs1 = [self getDateStrOfSeconds:3636*24*5];
DLog(@”timeDurationdecs1:%@”,timeDurationdecs1);
/**
6.将毫秒数换算成x天x时x分x秒x毫秒 这个方法和上面有点重复
*/
NSString *timeDurationdecs2 = [self getDateStrOfMSeconds:3638*24*5*1111];
DLog(@”timeDurationdecs2:%@”,timeDurationdecs2);
/*
7.比较日期大小默认会比较到秒
*/
Date1BelongTo belongToToday1 = [self compareOneDay:currDate withAnotherDay:currDate];
DLog(@”belongToToday1:%zd”,belongToToday1);
NSString *toDayStrPreciseAtmm = @”2016-12-2 10:13:23″;
NSDateFormatter *format = [[NSDateFormatter alloc]init];
format.dateFormat = @”yyyy-MM-dd HH:mm:ss”;
NSDate *oneDay = [format dateFromString:toDayStrPreciseAtmm];
Date1BelongTo belongToToday2 = [self compareOneDay:oneDay withAnotherDay:currDate];
DLog(@”belongToToday2:%zd”,belongToToday2);
NSString *dayFromPastStrPreciseAtmm = @”2016-12-1 10:13:23″;
NSDate *oneDay2 = [format dateFromString:dayFromPastStrPreciseAtmm];
Date1BelongTo belongToPast= [self compareOneDay:oneDay2 withAnotherDay:currDate];
DLog(@”belongToPast:%zd”,belongToPast);
NSString *dayFromFeatureStrPreciseAtmm = @”2016-12-3 10:13:23″;
NSDate *oneDay3 = [format dateFromString:dayFromFeatureStrPreciseAtmm];
Date1BelongTo belongToFeature = [self compareOneDay:oneDay3 withAnotherDay:currDate];
DLog(@”belongToFeature:%zd”,belongToFeature);
}
/**
1.NSDate实例/类 的基础使用
*/
-(void)basicisHandleOfNSDateInstanceOrClass{
NSDate*date=[NSDate date];
DLog(@”当下=%@”,date);
//比1970-1-1000晚100秒
[NSDate dateWithTimeIntervalSince1970:100];
DLog(@”dateWithTimeIntervalSince1970=%@”,[NSDate dateWithTimeIntervalSince1970:100]);
//比当前时间晚100秒
[NSDate dateWithTimeIntervalSinceNow:100];
DLog(@”dateWithTimeIntervalSinceNow=%@”,[NSDate dateWithTimeIntervalSinceNow:100]);
//随机返回一个将来的时间
[NSDate distantFuture];
DLog(@”distantFuture=%@”,[NSDate distantFuture]);
//随机访问一个过去的时间
[NSDate distantPast];
DLog(@”distantPast=%@”,[NSDate distantPast]);
NSDate*date2=[NSDate date];
//返回早一点的时间
DLog(@”earlierDate = %@”,[date earlierDate:date2]);
//返回晚一点的时间
DLog(@”laterDate = %@”,[date laterDate:date2]);
//返回从1970到现在的秒数
DLog(@”timeIntervalSince1970 %zd”,[date timeIntervalSince1970]);
//============================格式化使用=================================//
//格式化HH24小时hh12小时
NSDateFormatter*format=[[NSDateFormatter alloc]init];
format.dateFormat=@”yyyy-MM-dd hh:mm:ss”;
//时间转字符串输出
DLog(@”dateToformatStr=%@ class==%@”,[self NSDateToDateStrInSystemTz:date],[[self NSDateToDateStrInSystemTz:date] class]);
NSString*times=@”2014-02-02 12:10:25″;
//字符串转时间
DLog(@”dateFromString %@ class==%@”,[self dateStrToNSDtaeInSystemTz:times],[[self dateStrToNSDtaeInSystemTz:times] class]);
//===================设置固定时间差值=================================//
/**
设置两个时间的 差为固定值
*/
NSDate *currDate = [NSDate date];
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
NSDateComponents *comps = [[NSDateComponents alloc] init];
// [comps setYear:2];
// [comps setMonth:2];
[comps setDay:2];//设置最大时间为:当前时间推后2天
// [comps setHour:2];
// [comps setMinute:2];
// [comps setSecond:2];
NSDate *nextDate = [calendar dateByAddingComponents:comps toDate:currDate options:0];
DLog(@”固定时差 currDate:%@/n nextDate:%@/n”,currDate,nextDate);
//================计算两个日期之间的时间间隔======================//
NSDate *sixHourAgo = [currDate dateByAddingTimeInterval:-6*60*60];
NSTimeInterval tiemIntervalBetweenTwoDateInstance = [currDate timeIntervalSinceDate:sixHourAgo];
DLog(@”日期时间间隔 tiemIntervalBetweenTwoDateInstance:%f”,tiemIntervalBetweenTwoDateInstance);
/*******
-timeIntervalSinceNow 方法获取和当前的时间间隔
NSDate“实例”和“当前时间”的时间间隔
*********/
NSDate *anHourago = [NSDate dateWithTimeIntervalSinceNow:-60*60];
NSTimeInterval dateInstanceTimeIntervalSinceNow = [anHourago timeIntervalSinceNow];
DLog(@”日期时间间隔 %f”,dateInstanceTimeIntervalSinceNow);//结果: -3600.000007
}
/**
2.判断NSDate对应的是星期几
@param inputDate NSDate实例
@return 周几
*/
– (NSString*)weekdayStringFromDate:(NSDate*)inputDate {
// NSCalendar NSCalendarUnit NSDateComponents NSTimeZone
NSArray *weekdays = [NSArray arrayWithObjects: [NSNull null], @”星期天”, @”星期一”, @”星期二”, @”星期三”, @”星期四”, @”星期五”, @”星期六”, nil];
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
//…? 亚洲 上海这座城市为时区的标准
NSTimeZone *timeZone = [[NSTimeZone alloc] initWithName:@”Asia/Shanghai”];
[calendar setTimeZone: timeZone];
//?
NSCalendarUnit calendarUnit = NSCalendarUnitWeekday;
//?
NSDateComponents *theComponents = [calendar components:calendarUnit fromDate:inputDate];
return [weekdays objectAtIndex:theComponents.weekday];
}
/**
3.获取NSDate实例对应的是年月日
@param date NSDate实例
@return 哪年哪月哪日
*/
-(NSString*)getChineseCalendarWithDate:(NSDate *)date{
NSArray *chineseYears = [NSArray arrayWithObjects:
@”甲子”, @”乙丑”, @”丙寅”, @”丁卯”, @”戊辰”, @”己巳”, @”庚午”, @”辛未”, @”壬申”, @”癸酉”,
@”甲戌”, @”乙亥”, @”丙子”, @”丁丑”, @”戊寅”, @”己卯”, @”庚辰”, @”辛己”, @”壬午”, @”癸未”,
@”甲申”, @”乙酉”, @”丙戌”, @”丁亥”, @”戊子”, @”己丑”, @”庚寅”, @”辛卯”, @”壬辰”, @”癸巳”,
@”甲午”, @”乙未”, @”丙申”, @”丁酉”, @”戊戌”, @”己亥”, @”庚子”, @”辛丑”, @”壬寅”, @”癸丑”,
@”甲辰”, @”乙巳”, @”丙午”, @”丁未”, @”戊申”, @”己酉”, @”庚戌”, @”辛亥”, @”壬子”, @”癸丑”,
@”甲寅”, @”乙卯”, @”丙辰”, @”丁巳”, @”戊午”, @”己未”, @”庚申”, @”辛酉”, @”壬戌”, @”癸亥”, nil];
NSArray *chineseMonths=[NSArray arrayWithObjects:
@”正月”, @”二月”, @”三月”, @”四月”, @”五月”, @”六月”, @”七月”, @”八月”,
@”九月”, @”十月”, @”冬月”, @”腊月”, nil];
NSArray *chineseDays=[NSArray arrayWithObjects:
@”初一”, @”初二”, @”初三”, @”初四”, @”初五”, @”初六”, @”初七”, @”初八”, @”初九”, @”初十”,
@”十一”, @”十二”, @”十三”, @”十四”, @”十五”, @”十六”, @”十七”, @”十八”, @”十九”, @”二十”,
@”廿一”, @”廿二”, @”廿三”, @”廿四”, @”廿五”, @”廿六”, @”廿七”, @”廿八”, @”廿九”, @”三十”, nil];
NSCalendar *localeCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierChinese];
unsigned unitFlags = NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay;
NSDateComponents *localeComp = [localeCalendar components:unitFlags fromDate:date];
DLog(@”%zd_%zd_%zd”,localeComp.year,localeComp.month,localeComp.day);
NSString *y_str = [chineseYears objectAtIndex:localeComp.year-1];
NSString *m_str = [chineseMonths objectAtIndex:localeComp.month-1];
NSString *d_str = [chineseDays objectAtIndex:localeComp.day-1];
NSString *chineseCal_str =[NSString stringWithFormat: @”%@_%@_%@”,y_str,m_str,d_str];
return chineseCal_str;
}
/**
4.字符串转化成NSDate类型 计算与当前时间的相差 月数 天数
这个方法是将两个时间计算时间差处理
*/
-(void)computeDateWithTodayWithDateStr:(NSString*)dateStr{
NSDictionary *dic = @{
@”date”:@”2012-05-17 11:23:23″
};
if (kStringIsEmpty(dateStr)) {
dateStr = [dic objectForKey:@”date”];// 2012-05-17 11:23:23;
}
//日子字符串—>指定格式的NSDate实例
NSDateFormatter *format=[[NSDateFormatter alloc] init];
[format setDateFormat:@”yyyy-MM-dd HH:mm:ss”];
NSDate *fromdate=[format dateFromString:dateStr];
// 获取当前系统时区
NSTimeZone *fromzone = [NSTimeZone systemTimeZone];
// 获取刚才那个NSDate实例在与当前时区下的那个时间点,相差多少秒
NSTimeInterval frominterval = [fromzone secondsFromGMTForDate: fromdate];
//转换到当前时区下,同个时间点的当前时区的传进来的NSDate的表达
NSDate *fromDate = [fromdate dateByAddingTimeInterval: frominterval];
DLog(@”fromdate=%@”,fromDate);
// 注意:这里获取的时间要通过时区然后再转换为NSDate,不然转换为NSDate后和获取的字符串类型的日期 不一样
NSDate *date = [NSDate date];
NSTimeZone *zone = [NSTimeZone systemTimeZone];
NSTimeInterval interval = [zone secondsFromGMTForDate: date];
NSDate *localeDate = [date dateByAddingTimeInterval: interval];
DLog(@”enddate=%@”,localeDate);
// 注意:这里获系统的时间,为了确保准确性也要通过时区进行转换为本地的时间,如果直接用[NSDate date] 获取的时间和系统本地的时间不一样
NSCalendar *gregorian = [[NSCalendar alloc]initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
NSUInteger unitFlags = NSCalendarUnitMonth | NSCalendarUnitDay;
NSDateComponents *components = [gregorian components:unitFlags fromDate:fromDate toDate:localeDate options:0];
NSInteger months = [components month];
NSInteger days = [components day];//年[components year]
DLog(@”month=%zd”,months);
DLog(@”days=%zd”,days);
if (months==0&&days==0) {
dateStr=[[dateStr substringFromIndex:11]substringToIndex:5];
DLog(@”今天==>%@”,[NSString stringWithFormat:@”今天 %@”,dateStr]); //今天 11:23
}else if(months==0&&days==1){
dateStr=[[dateStr substringFromIndex:11]substringToIndex:5];
DLog(@”昨天==>%@”,[NSString stringWithFormat:@”昨天 %@”,dateStr]); //昨天 11:23
}else{
dateStr=[dateStr substringToIndex:10];
DLog(@”不是今天,也不是昨天的日子:%@”,dateStr);
}
}
/**
5.将秒转化为天,时,分,秒
@param seconds 总秒数
@return 时长秒数字符串
*/
-(NSString*)getDateStrOfSeconds:(long)seconds{
if(seconds < 0){
return @”秒数必须大于0″;
}
long one_day = 60 * 60 * 24;
long one_hour = 60 * 60;
long one_minute = 60;
long day,hour,minute,second = 0L;;
day = seconds / one_day;
hour = seconds % one_day / one_hour ;
minute = seconds % one_day % one_hour / one_minute;
second = seconds % one_day % one_hour % one_minute;
if(seconds < one_minute){
return [NSString stringWithFormat:@”%ld秒”,second];
}else if(seconds >= one_minute && seconds < one_hour){
return [NSString stringWithFormat:@”%ld分%ld秒”,minute,second];
}else if (seconds >= one_hour && seconds < one_day){
return [NSString stringWithFormat:@”%ld时%ld分%ld秒”,hour,minute,second];
}else{
return [NSString stringWithFormat:@”%ld天%ld时%ld分%ld秒”,day,hour,minute,second] ;
}
}
/**
6.将毫秒数换算成x天x时x分x秒x毫秒 这个方法和上面有点重复
@return x天x时x分x秒x毫秒
*/
-(NSString*)getDateStrOfMSeconds:(long )ms{
int ss = 1000;
int mi = ss * 60;
int hh = mi * 60;
int dd = hh * 24;
long day = ms / dd;
long hour = (ms – day * dd) / hh;
long minute = (ms – day * dd – hour * hh) / mi;
long second = (ms – day * dd – hour * hh – minute * mi) / ss;
long milliSecond = ms – day * dd – hour * hh – minute * mi – second * ss;
NSString* strDay = (day >0) ? [NSString stringWithFormat:@”%ld”,day] : [NSString stringWithFormat:@”0%ld”, day];
NSString* strHour = (hour >0) ? [NSString stringWithFormat:@”%ld”,hour] : [NSString stringWithFormat:@”0%ld”, hour];
NSString* strMinute = (minute >0)? [NSString stringWithFormat:@”%ld”,minute] : [NSString stringWithFormat:@”0%ld”, minute];
NSString* strSecond = (second >0) ? [NSString stringWithFormat:@”%ld”,second] : [NSString stringWithFormat:@”0%ld”, second];
NSString* strMilliSecond = (milliSecond >0) ? [NSString stringWithFormat:@”%ld”,milliSecond] : [NSString stringWithFormat:@”0%ld”, milliSecond];
// strMilliSecond = milliSecond < 100 ? “0” + strMilliSecond : “” + strMilliSecond;
return [NSString stringWithFormat:@”[email protected][email protected][email protected][email protected][email protected]“,strDay,strHour,strMinute,strSecond,strMilliSecond];
}
/*
7.比较日期大小
*/
-(Date1BelongTo)compareOneDay:(NSDate *)oneDay withAnotherDay:(NSDate *)anotherDay
{
if ([oneDay isEqualToDate:anotherDay]) {
return Date1BelongToToday;
}else{
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
[dateFormatter setDateFormat:@”yyyy-MM-dd “];//@”yyyy-MM-dd HH:mm:ss”这里只关心日期是不是同一天,我们不必理会时分秒
dateFormatter.timeZone = [NSTimeZone systemTimeZone];
NSString *oneDayStr = [dateFormatter stringFromDate:oneDay];
NSString *anotherDayStr = [dateFormatter stringFromDate:anotherDay];
NSDate *dateA = [dateFormatter dateFromString:oneDayStr];
NSDate *dateB = [dateFormatter dateFromString:anotherDayStr];
NSComparisonResult result = [dateA compare:dateB];
DLog(@”date1 : %@, date2 : %@”, oneDay, anotherDay);
switch (result) {
case NSOrderedDescending:
{
DLog(@”Date1 is in the future”);
return Date1BelongToFeature;
}
break;
case NSOrderedAscending:
{
DLog(@”Date1 is in the past”);
return Date1BelongToPast;
}
break;
case NSOrderedSame:
{
DLog(@”Both dates are the same”);
return Date1BelongToToday;
}
break;
}
// if (result == NSOrderedDescending) {
// DLog(@”Date1 is in the future”);
// return Date1BelongToFeature;
// }
// else if (result ==NSOrderedAscending){
// DLog(@”Date1 is in the past”);
// return Date1BelongToPast;
// }else{
//
// DLog(@”Both dates are the same”);
// return Date1BelongToToday;
// }
}
}
//日期字符串转换成NSDate对象===>已经是系统当前时区
-(NSDate*)dateStrToNSDtaeInSystemTz:(NSString*)dateStr{
//日期字符串===>NSDate===>当前时区下的NSDate
if (!kStringIsEmpty(dateStr)) {
NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
formatter.dateFormat = @”yyyy-MM-dd HH:mm:ss”;
//默认认为是当前时区下的日期字符串 转换为 官方时区下的NSDate实例====>美国时区
NSDate *dateFromDateStr = [formatter dateFromString:dateStr];
DLog(@”dateStr:%@,dateFromDateStr%@”,dateStr,dateFromDateStr);
NSTimeZone *systemTz = [NSTimeZone systemTimeZone];
NSTimeInterval tI = [systemTz secondsFromGMTForDate:dateFromDateStr];
NSDate *trulyDate = [dateFromDateStr dateByAddingTimeInterval:tI];
DLog(@”trulyDate:%@”,trulyDate);
return trulyDate;
}else{
return nil;
}
}
//date转换成当前时区下的字符串
-(NSString*)NSDateToDateStrInSystemTz:(NSDate*)date{
//日期字符串===>NSDate===>当前时区下的NSDate
if (!kObjectIsEmpty(date)) {
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
dateFormatter.dateFormat = @”yyy-MM-dd HH:mm:ss”;
dateFormatter.timeZone = [NSTimeZone systemTimeZone];//默认是美国时区
return [dateFormatter stringFromDate:date];
}else{
return nil;
}
}
//NSdate转换成NSDate对象===>转换为系统当前时区
-(NSDate*)dateOfSystemTzWithDateInstance:(NSDate*)date{
//NSDate实例—->当前系统时区—->时差(实例默认是美国时间时区,实例在两个时区之间的时差。是加上时差还是减去时差,就得看具体场景了<经纬度问题>)—–>当前系统下,NSDate实例对应的时间
NSDate *currDate = [NSDate date];
if (!date) {
date = currDate;
}
DLog(@”currDate:%@”,date);
NSTimeZone *systemTimeZone = [NSTimeZone systemTimeZone];
NSTimeInterval currDateTICmpWithWesternTZ = [systemTimeZone secondsFromGMTForDate:date];
DLog(@”currDateTICmpWithWesternTZ:%zd”,currDateTICmpWithWesternTZ);
NSDate *currDateInSystemTZ = [currDate dateByAddingTimeInterval:currDateTICmpWithWesternTZ];
return currDateInSystemTZ;
}
/*********
比较两个日期之间的差值
*******/
– (NSDateComponents*)differencewithDate:(NSString*)dateString withDate:(NSString*)anotherdateString{
// _created_at == Thu Oct 16 17:06:25 +0800 2014
// dateFormat == EEE MMM dd HH:mm:ss Z yyyy
// NSString –> NSDate
NSDateFormatter *fmt = [[NSDateFormatter alloc]init];
// 如果是真机调试,转换这种欧美时间,需要设置locale
fmt.locale = [[NSLocale alloc]initWithLocaleIdentifier:@”en_US”];
// 设置日期格式(声明字符串里面每个数字和单词的含义)
// E:星期几
// M:月份
// d:几号(这个月的第几天)
// H:24小时制的小时
// m:分钟
// s:秒
// y:年
fmt.dateFormat =@”EEE MMM dd HH:mm:ss Z yyyy”;
// 微博的创建日期
NSDate *createDate = [fmt dateFromString:dateString];
// 当前时间
NSDate *now = [NSDate date];
// 日历对象(方便比较两个日期之间的差距)
NSCalendar *calendar = [NSCalendar currentCalendar];
// NSCalendarUnit枚举代表想获得哪些差值
NSCalendarUnit unit =NSCalendarUnitYear |NSCalendarUnitMonth|NSCalendarUnitDay |NSCalendarUnitHour |NSCalendarUnitMinute|NSCalendarUnitSecond;
// 计算两个日期之间的差值
NSDateComponents *cmps = [calendar components:unit fromDate:createDate toDate:now options:0];
DLog(@”%@ %@ %@”, createDate, now, cmps);
return cmps;
}
原创文章,作者:奋斗,如若转载,请注明出处:https://blog.ytso.com/6062.html