IOS-NSDate之今天,昨天,这周,这个月,上个月
2015-06-23 19:39
525 查看
今天跟大家讨论日期的用法,相信大家在项目中,经常会设置一个默认时间段,比如一周前到今天。下面教大家怎么获取前一天,或前一周等等。
比如date
2009-12-11
比如date
2009-12-11
NSDate *today = [NSDate dateWithString:@"2009-12-11 00:00:00 +0000"]; NSDate *yesterday = [NSDate dateWithString:@"2009-12-10 00:00:00 +0000"]; NSDate *thisWeek = [NSDate dateWithString:@"2009-12-06 00:00:00 +0000"]; NSDate *lastWeek = [NSDate dateWithString:@"2009-11-30 00:00:00 +0000"]; NSDate *thisMonth = [NSDate dateWithString:@"2009-12-01 00:00:00 +0000"]; NSDate *lastMonth = [NSDate dateWithString:@"2009-11-01 00:00:00 +0000"]; 要求出上面的时间 NSCalendar *cal = [NSCalendar currentCalendar]; NSDateComponents *components = [cal components:( NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit ) fromDate:[[NSDate alloc] init]]; [components setHour:-[components hour]]; [components setMinute:-[components minute]]; [components setSecond:-[components second]]; NSDate *today = [cal dateByAddingComponents:components toDate:[[NSDate alloc] init] options:0]; //This variable should now be pointing at a date object that is the start of today (midnight); [components setHour:-24]; [components setMinute:0]; [components setSecond:0]; NSDate *yesterday = [cal dateByAddingComponents:components toDate: today options:0]; components = [cal components:NSWeekdayCalendarUnit | NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit fromDate:[[NSDate alloc] init]]; [components setDay:([components day] - ([components weekday] - 1))]; NSDate *thisWeek = [cal dateFromComponents:components]; [components setDay:([components day] - 7)]; NSDate *lastWeek = [cal dateFromComponents:components]; [components setDay:([components day] - ([components day] -1))]; NSDate *thisMonth = [cal dateFromComponents:components]; [components setMonth:([components month] - 1)]; NSDate *lastMonth = [cal dateFromComponents:components]; NSLog(@"today=%@",today); NSLog(@"yesterday=%@",yesterday); NSLog(@"thisWeek=%@",thisWeek); NSLog(@"lastWeek=%@",lastWeek); NSLog(@"thisMonth=%@",thisMonth); NSLog(@"lastMonth=%@",lastMonth);
相关文章推荐
- iOS 6 Auto Layout NSLayoutConstraint 界面布局
- 猫猫学iOS之小知识iOS启动动画_Launch Screen的运用
- iOS 打包32bit&64 universal-framework
- IOS学习之NSTimer使用详解
- iOS文字大小自适应库(MBFontAdapter)诞生记
- IOS学习之定时器NSTimer的开启与关闭
- iOS AES解密 我遇到的问题
- iOS 目录的使用
- IOS8下,百度地图无法定位解决办法
- IOS开发 根据某个日期计算是星期几
- iOS之JSONKit解析JSON
- iOS开发ARC下内存管理
- iOS之NSJSONSerialization对json解析
- ios view截图
- iOS view模糊背景
- iOS CAGradientLayer 颜色渐变
- 消消乐无限道具BUG
- ios修改textField的placeholder的字体颜色、大小
- iOS 8 毛玻璃效果
- iOS TableView实现QQ好友列表(三)