平时在在计算日期的时候都会用到有关计算方面的东西,今天刚好也用到了,网上有的用法已经过期,不能用了,所以今天整理了一下。
用到的类是 NSDate,NSCalendar,NSDateComponents。
NSDate使用的是绝对的时间。
NSCalendar与TimeZone相关,它会根据TimeZone解释NSDateComponents的意义。比如例子中,[timeZoneCompssetHour:16];此时,经过NSCalendar的解释,它就变成了CDT(美国中部时间)的下午4点钟,也就是5:00EDT(美国东部时间)。
NSDateComponents可以认为是一个保存了int year, int month, int day, inthour, int minute, int second变量的一个对象。它没有直接保存为一个date对象。当需要获取NSDate的时候,才动态的计算得到。并且,每个变量都可以是正数,也可以是负数和0。
这些就可以帮助我们进行一些时间的计算
声明这些
NSDate * currentDate = [NSDate date];
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents*comps;
// 年,月,日 获得
comps =[calendar components:(NSCalendarUnitYear | NSCalendarUnitMonth |NSCalendarUnitDay)
fromDate:currentDate];
NSInteger year = [comps year];
NSInteger month = [comps month];
NSInteger day = [comps day];
NSLog(@"year:%d month: %d, day: %d", year, month, day);
// 小时,分,秒
comps =[calendar components:(NSCalendarUnitHour | NSCalendarUnitMinute |NSCalendarUnitSecond)
fromDate:currentDate];
NSInteger hour = [comps hour];
NSInteger minute = [comps minute];
NSInteger second = [comps second];
NSLog(@"hour:%d minute: %d second: %d", hour, minute, second);
// 星期几的获得
comps =[calendar components:(NSCalendarUnitWeekOfMonth | NSCalendarUnitWeekday |NSCalendarUnitWeekdayOrdinal)
fromDate:currentDate];
//NSCalendarUnitWeekOfMonth 这个月的第几周
//NSCalendarUnitWeekOfYear 这个年的第几周
NSInteger week = [comps weekOfYear]; // 今年的第几周
NSInteger weekday = [comps weekday]; // 星期几(注意,周日是“1”,周一是“2”。。。。)
NSInteger weekdayOrdinal = [comps weekdayOrdinal]; // 这个月的第几周
NSLog(@"week:%d weekday: %d weekday ordinal: %d", week, weekday, weekdayOrdinal);
这里要特别注意的是日期的开始是周日大家可以写一个语句转换一下
NSString * weekstr = nil;
switch (weekday) {
case 1:
weekstr = @"星期日";
break;
case 2:
weekstr = @"星期一";
break;
case 3:
weekstr = @"星期二";
break;
case 4:
weekstr = @"星期三";
break;
case 5:
weekstr = @"星期四";
break;
case 6:
weekstr = @"星期五";
break;
case 7:
weekstr = @"星期六";
break;
default:
break;
}
//时间格式的转换
// 时间格式
NSDateFormatter*dateFormatter = [[NSDateFormatter alloc]init];
if(/* DISABLES CODE */ (1))
[dateFormatter setDateFormat:@"dd-MMM-yyy,hh:mm:ss"];
else
[dateFormatter setDateFormat:@"hh:mm:ss"];
NSString * dataStr = [dateFormatter stringFromDate:[NSDate date]];
NSLog(@"日期:%@",dataStr);
// 创建一定时间间隔的NSDate对象,这个是以当前的日期为准来创建昨天和明天的时间
NSTimeInterval secondsPerDay = 24 * 60 * 60;
NSDate *tomorrow = [[NSDate alloc] initWithTimeIntervalSinceNow:secondsPerDay];
NSDate *yesterday = [[NSDate alloc] initWithTimeIntervalSinceNow:-secondsPerDay];
// 任意时间的明天
NSTimeInterval secondsPerDay = 24 * 60 * 60;
NSDate * date = [NSDate date];
NSDate * tomorrow = [date dateByAddingTimeInterval: secondsPerDay];
//任意时间的昨天
NSTimeInterval secondsPerDay = 24 * 60 * 60;
NSDate * date = [NSdate date];
NSDate * tomorrow = [date dateByAddingTimeInterval:-secondsPerDay];
自己写的Demo
https://github.com/thinkma/NSdate.git
可以看看