近来用到时间空间,整理一些可能用到的处理NSDate的方法和大家分享,有什么不足的欢迎大家补充。
//获取当前时间前后几年几月几天的时间year=1是当前时间的后一年year=-1时当前的前一年,月和日也是一样
-(void)getTime
{
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
NSDateComponents *comps = nil;
comps = [calendar components:NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay fromDate:[NSDate date]];
NSDateComponents *adcomps = [[NSDateComponents alloc] init];
[adcomps setYear:year];
[adcomps setMonth:month];
[adcomps setDay:day];
NSDate *newdate = [calendar dateByAddingComponents:adcomps toDate:[NSDate date] options:0];
NSDateFormatter *pickerFormatter = [[NSDateFormatter alloc] init];// 创建一个日期格式器
[pickerFormatter setDateFormat:@"yyyy-MM"];
NSString *dateString = [pickerFormatter stringFromDate:newdate];
return dateString;
}
比较时间的大小
[localDate compare:date8]==NSOrderedDescending
[localDate compare:date20]==NSOrderedAscending
NSOrderedSame
比较,取得更早或更晚的日期:
NSDate *d = [date1 earlierDate: date2];
NSDate *d = [date1 laterDate: date2]
是否相同日期:
BOOL b = [date1 isEqualToDate: date2];
从某时间开始经过某秒后的日期时间:
bDate = [aDate initWithTimeInterval:3*60 sinceDate:aDate]; //从aDate过3分钟
指定某月的末日: (使用前一个月的第一天来取得)
NSDate *aDate = [inputDateFormatter dateFromString:@"2000/03/01 00:00:00"]; //给定3月1日零点日期
NSDate *bDate = [orgDate initWithTimeInterval:-1*24*60*60 sinceDate:a];// 1日前
NSLog(@"2000年2月的末日 -> %@", bDate);
取得某两个时间相隔多久:
since = [dateA timeIntervalSinceDate: dateB];
只取得日期不要时间:
NSDateFormatter *df = [[NSDateFormatter alloc] init];
[df setTimeStyle: NSDateFormatterNoStyle];
[df setDateStyle: NSDateFormatterMediumStyle];
NSString *nowDateStr = [df stringFromDate:[NSDate date]];
NSDate *nowDate = [df dateFromString:nowDateStr];
NSLog(@"%@", nowDate);
2.获取当前所处时区
NSTimeZone *zone = [NSTimeZone systemTimeZone];
NSLog(@"now = %@", zone);
3.获取当前时区和指定时间差
NSInteger seconds = [zone secondsFromGMTForDate:date];
NSLog(@"seconds = %lu", seconds);
NSDate *nowDate = [date dateByAddingTimeInterval:seconds];
NSLog(@"nowDate = %@", nowDate);
//比较两个日期的差值
// 时间字符串
NSString *str = @"2012-03-11 06:44:11 +0800";
// 1.创建一个时间格式化对象
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
// 2.格式化对象的样式/z大小写都行/格式必须严格和字符串时间一样
formatter.dateFormat = @"yyyy-MM-dd HH:mm:ss Z";
// 3.字符串转换成时间/自动转换0时区/东加西减
NSDate *date = [formatter dateFromString:str];
NSDate *now = [NSDate date];
// 注意获取calendar,应该根据系统版本判断
NSCalendar *calendar = [NSCalendar currentCalendar];
NSCalendarUnit type = NSCalendarUnitYear |
NSCalendarUnitMonth |
NSCalendarUnitDay |
NSCalendarUnitHour |
NSCalendarUnitMinute |
NSCalendarUnitSecond;
// 4.获取了时间元素
NSDateComponents *cmps = [calendar components:type fromDate:date toDate:now options:0];
NSLog(@"%ld年%ld月%ld日%ld小时%ld分钟%ld秒钟", cmps.year, cmps.month, cmps.day, cmps.hour, cmps.minute, cmps.second);