iOS小技能: 日曆的使用(案例:兩個時間的比較、獲取最近30天的資料)
“我正在參加「掘金·啟航計劃」”
引言
預備知識:日曆識別符號NSCalendarIdentifier
```objectivec
NSCalendarIdentifierGregorian //公曆
NSCalendarIdentifierBuddhist //佛_教日曆
NSCalendarIdentifierChinese //中_國農曆
NSCalendarIdentifierHebrew //希_伯來日曆
NSCalendarIdentifierIslamic //伊_斯蘭日曆
NSCalendarIdentifierIslamicCivil //伊_斯蘭教日曆
NSCalendarIdentifierJapanese //日_本日曆
NSCalendarIdentifierRepublicOfChina //中_華民_國日曆(臺灣)
NSCalendarIdentifierPersian //波_斯歷
NSCalendarIdentifierIndian //印_度日曆
NSCalendarIdentifierISO8601 //ISO8601
```
I 日曆的使用
1.1 兩個時間的比較(NSDateComponents)
案例1: 計算兩個時間的間隔(天)
```objectivec /** 計算兩個時間的間隔(天)
@param start 開始時間 @param end 結束時間 @return 間隔時間 / + (NSInteger)contrastTimeBackDayWithStartDate:(NSString )start endDate:(NSString *)end { NSTimeInterval time = [self contrastTimeWithyyyyMMddStartDate:start endDate:end]; NSInteger minute,second,hour,day; second=(NSInteger)time%1000; minute = (NSInteger)(time/60)%60; hour = (NSInteger)(time/3600)%24; day = (time/3600/24); return day; }
/** 計算兩個時間的間隔(毫秒)
@param start 開始時間 @param end 結束時間 @return 間隔時間 / + (NSTimeInterval)contrastTimeWithyyyyMMddStartDate:(NSString )start endDate:(NSString )end { NSDateFormatter dateFormatter = [[NSDateFormatter alloc] init]; // [dateFormatter setDateFormat:@"yyyy-MM-dd"];
[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm"];
NSDate *startDate = [dateFormatter dateFromString:start];
NSDate *endDate = [dateFormatter dateFromString:end];
NSTimeInterval time = [endDate timeIntervalSinceDate:startDate];
return time;
}
```
案例2:處理微博的釋出時間
```objectivec / 處理今年的時間 / - (NSString)setupDateInThisYear:(NSDate)tmpDate{ NSCalendarUnit calendarUnit = NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay|NSCalendarUnitHour|NSCalendarUnitMinute; NSDateComponents dateComponents = [self dateComponentsWithFromDate:tmpDate toDate:[NSDate date] calendarUnit:calendarUnit]; if ([self isToday:dateComponents]) { /1》一天之內的時間處理/ return [self setupTodayTime:dateComponents]; }else if ([self isYesterDay:dateComponents]){ /2》25-48小時後的時間處理(24小時之後) yesterday HH:mm yesterday 17:30 兩天之內 (48小時之內)25-48小時之內/ return [NSString stringWithFormat:@"yesterday %@",[self stringFromDate:tmpDate dateformatter:@"HH:mm" localeIdentifier:@"en_US"]]; }else{ /3》48小時後的時間處理(其它時間) MM-dd HH:mm 09-18 17:30 48小時之後*/ return [self stringFromDate:tmpDate dateformatter:@"MM-dd HH:mm" localeIdentifier:@"en_US"]; }
} ```
1.2 時間獲取
iOS 獲取時間的應用場景: 報表的時間篩選
- 獲取上個月
self.viewModel.multipleSwitchCellTableViewCellModel.MonthlyDateStr = [QCT_Common strdate4lastMonthlyStrYYMM];
```objectivec /* 獲取上個月份字串 / -
(NSString )strdate4lastMonthlyStrYYMM{
NSDate currentDate = [NSDate date];NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar]; NSDateComponents *lastMonthComps = [[NSDateComponents alloc] init];
// [lastMonthComps setYear:1]; // year = 1表示1年後的時間 year = -1為1年前的日期,month day 類推 [lastMonthComps setMonth:-1]; NSDate *newdate = [calendar dateByAddingComponents:lastMonthComps toDate:currentDate options:0];
NSString tmpbirthday = @""; tmpbirthday = [QCT_Common date4YYMM:newdate]; NSLog(@"date str = %@", tmpbirthday); // NSDateFormatter formatter = [[NSDateFormatter alloc] init]; // [formatter setDateFormat:@"yyyy-MM"]; // NSString *dateStr = [formatter stringFromDate:newdate];
return tmpbirthday; }
```
- 獲取本月 ```objectivec /* 獲取當前月份字串 /
-
(NSString *)strdate4TodaydateMonthlyStrYYMM{
NSDate *lastDay =[NSDate date];//
// NSDate lastDay = [NSDate dateWithTimeInterval:-2460*60 sinceDate:[NSDate date]];//前一天
NSString *tmpbirthday = @"";
tmpbirthday = [QCT_Common date4YYMM:lastDay];
return tmpbirthday;
}
```
- 獲取前一天
```objectivec + (NSString *)strdate4lastDayYYMMDD{
NSDate *lastDay = [NSDate dateWithTimeInterval:-24*60*60 sinceDate:[NSDate date]];//前一天
NSString *tmpbirthday = @"";
tmpbirthday = [QCT_Common date4YYMMDD:lastDay];
return tmpbirthday;
}
```
- 獲取30天前的日期
使用日曆NSCalendar獲取時間:根據日期元件
NSDateComponents
的引數配置獲取日期時間- (NSDate *)dateByAddingComponents:(NSDateComponents *)comps toDate:(NSDate *)date options:(NSCalendarOptions)opts;
```objectivec / 獲取30天前的日期:格式YY-MM-DD 2022-08-06 / + (NSString )strdate4lastMonthlyStrYYMMDD{
NSDate *currentDate = [NSDate date];
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
NSDateComponents *lastMonthComps = [[NSDateComponents alloc] init];
// [lastMonthComps setYear:1]; // year = 1表示1年後的時間 year = -1為1年前的日期,month day 類推
// [lastMonthComps setMonth:-1];
[lastMonthComps setDay:-30];
NSDate *newdate = [calendar dateByAddingComponents:lastMonthComps toDate:currentDate options:0];
NSString *tmpbirthday = @"";
tmpbirthday = [QCT_Common date4YYMMDD:newdate];
NSLog(@"date str = %@", tmpbirthday);//date str = 2022-08-06
return tmpbirthday;
}
```
II 案例
2.1 構造退款單號
商戶退款單號(商戶退款單號,32個字元內、可包含字母,確保在商戶系統唯一。同個退款單號多次請求,平臺當一個單處理,只會退一次款。如果出現退款不成功,請採用原退款單號重新發起,避免出現重複退款。)
商戶退款單號(out_refund_no):yyMMddHHmmss + xxxxxx(sid)+ 遞增序號(隔天重置)
```objectivec - (NSString *)out_refund_no{
NSMutableString *str = [[NSMutableString alloc]initWithString: [QCT_Common getyyMMddHHmmss4TodayTime]];
[str appendString:xxx.id];
[str appendString:QCTSession.shareQCTSession.snid];
return str;
}
```
- snid(遞增序號(隔天重置))
```objectivec
/** yyMMddHHmmss + xxxxxx(6位sid)+ 5位序號
/ - (NSString )snid{
// 先從偏好獲取物件,如果不存在就進行儲存
NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
NSMutableDictionary *k_sndi_keydic = [NSKeyedUnarchiver unarchiveObjectWithData:[[NSUserDefaults standardUserDefaults] dataForKey:k_sndi_key]];
NSString *str =@"00000";
NSString *todayStr = [QCT_Common date4YYMMDD:[NSDate date]];
if([k_sndi_keydic.allKeys containsObject:k_sndi_date_key]){
NSString *lastday = k_sndi_keydic[k_sndi_date_key];
str = [[NSMutableString alloc]initWithString: k_sndi_keydic[k_sndi_key]];
if([todayStr isEqualToString:lastday]){
int d = [str intValue]+1;
NSNumber *t = [NSNumber numberWithInt:d];
str = [QCT_Common addComplementspaces:t.description count:5 placeholder:@"0" isdirectionRight:NO];//
}else{
str = @"00000";
[k_sndi_keydic setValue:todayStr forKey:k_sndi_date_key];
}
}else{
k_sndi_keydic = [NSMutableDictionary dictionary];
[k_sndi_keydic setValue:todayStr forKey:k_sndi_date_key];
str = @"00000";
}
[k_sndi_keydic setValue:str forKey:k_sndi_key];
NSData *data = [NSKeyedArchiver archivedDataWithRootObject: k_sndi_keydic];
[user setValue:data forKey:k_sndi_key];
[user synchronize];
NSLog(@"str:%@",FMSTR(@"%@",str));//02022
return str;
}
```
- 補齊特定符號方案
http://kunnan.blog.csdn.net/article/details/104018151
```objectivec /**
str: 原字串 count: 補齊到第幾位
placeholder: 補齊的符號
isdirectionRight: 是否往右補齊 / + (NSString)addComplementspaces:(NSString)str count:(NSInteger)count placeholder:(NSString)placeholder isdirectionRight:(BOOL)isdirectionRight{
NSLog(@"addComplementspacesstr:%@",FMSTR(@"%@",str));//02022
if (str.length>=count) {
return str;
}
NSMutableString *tmp = [NSMutableString new];
if(isdirectionRight){
tmp = [[NSMutableString alloc]initWithString:str];// 右補齊
}
NSInteger tmpcount = count -str.length;
for (int i =0; i< tmpcount; i++) {
[tmp appendString:placeholder];// 補齊
}
if(!isdirectionRight){
[tmp appendString:str];// 往左補齊
}
NSLog(@"addComplementspacesstr:%@",FMSTR(@"%@",tmp.description));//02022
return tmp.description;
}
```
2.2 計算兩個時間的間隔(天)
工具方法:計算兩個時間的間隔(天)
```objectivec /** 計算兩個時間的間隔(天)
@param start 開始時間 @param end 結束時間 @return 間隔時間 / + (NSInteger)contrastTimeBackDayWithStartDate:(NSString )start endDate:(NSString *)end { NSTimeInterval time = [self contrastTimeWithyyyyMMddStartDate:start endDate:end]; NSInteger minute,second,hour,day; second=(NSInteger)time%1000; minute = (NSInteger)(time/60)%60; hour = (NSInteger)(time/3600)%24; day = (time/3600/24); return day; }
/** 計算兩個時間的間隔(毫秒)
@param start 開始時間 @param end 結束時間 @return 間隔時間 / + (NSTimeInterval)contrastTimeWithyyyyMMddStartDate:(NSString )start endDate:(NSString )end { NSDateFormatter dateFormatter = [[NSDateFormatter alloc] init]; // [dateFormatter setDateFormat:@"yyyy-MM-dd"];
[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm"];
NSDate *startDate = [dateFormatter dateFromString:start];
NSDate *endDate = [dateFormatter dateFromString:end];
NSTimeInterval time = [endDate timeIntervalSinceDate:startDate];
return time;
}
```
例子1:限制時間範圍為30天 ```objectivec NSInteger day = [QCT_Common contrastTimeBackDayWithStartDate:weakSelf.filterViewModel.timeModel.startStr endDate:weakSelf.filterViewModel.timeModel.endStr]; NSLog(@"day: %ld",(long)day);
if (day > 29) {
[weakSelf showHUDMessage:QCTLocal(@"time_interval_should_not_exceed_30_days")];
return;
}
```
例子2: 資料過濾: 獲取最近7天的資料
```objectivec
// 資料過濾: 獲取最近7天的資料
NSMutableString str = [[NSMutableString alloc]initWithString: [QCT_Common get4TodayTimeWithDateFormat:@"yyyy-MM-dd HH:mm:ss"]];
NSMutableArray tmp = [NSMutableArray array];
for (QCTReceiptDetailModel *obj in tmparr) {
NSInteger day = [QCT_Common contrastTimeBackDayWithStartDate:obj.completeTime endDate:str DateFormat:@"yyyy-MM-dd HH:mm:ss"];// endDate 大
NSLog(@"day: %ld",(long)day);
if (day > 6) {
}else{
[tmp addObject:obj];
}
}
```
2.3 時間格式化
http://blog.csdn.net/z929118967/article/details/124838767
see also
iOS隱私安全:使用者協議及隱私政策彈框(包含超連結屬性、demo支援中英文切換)http://kunnan.blog.csdn.net/article/details/103902362
- iOS小技能:UITableView的適配 (iOS10/iOS14/iOS16.0)
- iOS小技能:和uni-app、unity的融合方案
- iOS小技能:iOS15崩潰排查技巧(symbolicatecrash符號化分析問題、匯出和隱藏符號)
- iOS小技能:【intercept the HTTP/HTTPS requests 】利用NSURLProtocol 攔截請求
- iOS小技能: tweak 整合CocoaAsyncSocket(建連、斷開、重連、心跳、通用請求)
- iOS小技能:iOS13 證件掃描 & 文字識別API
- iOS小技能:整合下拉重新整理控制元件 & 實現無感知上拉載入更多
- iOS小技能:程式碼觸發button的點選事件、快速找到按鈕action方法
- iOS小技能:撥號、發郵件、簡訊、應用間跳轉
- iOS小技能:鏈式程式設計在iOS開發中的應用
- iOS小技能:iOS14 讀取使用者剪下板資料彈出提示的相容方案
- iOS小技能:因境外IP無法訪問導致 App 被拒的解決方案
- iOS小技能:RSA簽名、驗籤、加密、解密的原理
- iOS小技能:Xcode14新特性(適配)
- iOS小技能:Socket基礎知識
- iOS小技能:SKU檢視搭建
- iOS小技能: 日曆的使用(案例:兩個時間的比較、獲取最近30天的資料)
- iOS小技能:1. iOS 實現json資料提交 2. 對同一個URL的多次請求進行資料快取 3. 檢查網路狀態
- iOS小技能:使用正則表示式對聊天記錄的關鍵詞進行監控
- iOS小技能:去掉/新增導航欄黑邊(iOS13適配)