在自己的項目中有這個需求,在網上找了下,沒有找到理想的結果,就東拼西湊的把大家的想法,集合在一起,加上自己的想法,實現了這個功能。
溫馨提示:測試了將來某個日期是星期幾,未測試過去的某個日期是星期幾
實現思路
大概的實現方式和大家分享下,有不對的地方歡迎大家留言指教,相互學習
首先計算 未來的 某個日期 和 當前日期相差天數
在獲取當前是星期幾(返回結果如下格式)
1 2 3 4 5 6 7 | 1--星期天 2--星期一 3--星期二 4--星期三 5--星期四 6--星期五 7--星期六 |
最後在當前星期 基礎上 加上 相差天數,就獲取未來那個日期所對應的星期(此處可以將 (相差天數 % 7),結果就更加明瞭相差的天數(結果是0,說明未來的某個日期的星期就是對應當前的星期),7代表的一週共7天
實現代碼
代碼中本人已經寫了很詳細的說明,在這裏就一一單獨說了,代碼分爲3段,如下
第一段代碼:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
|
/**
* 獲取未來某個日期是星期幾
* 注意:featureDate 傳遞過來的格式 必須 和 formatter.dateFormat 一致,否則endDate可能爲nil
*
*/
-
(NSString
*)featureWeekdayWithDate:(NSString
*)featureDate{
//
創建 格式 對象
NSDateFormatter
*formatter
=
[[NSDateFormatter
alloc]
init];
//
設置 日期 格式 可以根據自己的需求 隨時調整, 否則計算的結果可能爲 nil
formatter.dateFormat
=
@"yyyy-MM-dd";
//
將字符串日期 轉換爲 NSDate 類型
NSDate
*endDate
=
[formatter
dateFromString:featureDate];
//
判斷當前日期 和 未來某個時刻日期 相差的天數
long
days
=
[self
daysFromDate:[NSDate
date]
toDate:endDate];
//
將總天數 換算爲 以 周 計算(假如 相差10天,其實就是等於 相差 1周零3天,只需要取3天,更加方便計算)
long
day
=
days
>=
7
?
days
%
7 : days;
long
week
=
[self
getNowWeekday]
+
day;
switch
(week)
{
case
1:
return
@"星期天";
break;
case
2:
return
@"星期一";
break;
case
3:
return
@"星期二";
break;
case
4:
return
@"星期三";
break;
case
5:
return
@"星期四";
break;
case
6:
return
@"星期五";
break;
case
7:
return
@"星期六";
break;
default:
break;
}
return
nil;
}
|
第二段代碼
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | /** * 計算2個日期相差天數 * startDate 起始日期 * endDate 截至日期 */ -(NSInteger)daysFromDate:(NSDate *)startDate toDate:(NSDate *)endDate { NSDateFormatter *dateFormatter=[[NSDateFormatter alloc] init]; // 話說在真機上需要設置區域,才能正確獲取本地日期,天朝代碼:zh_CN dateFormatter.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"zh_CN"]; [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"]; //得到相差秒數 NSTimeInterval time = [endDate timeIntervalSinceDate:startDate]; int days = ((int)time)/(3600*24); int hours = ((int)time)%(3600*24)/3600; int minute = ((int)time)%(3600*24)/3600/60; if (days <= 0 && hours <= 0&&minute<= 0) { NSLog(@"0天0小時0分鐘"); return 0; } else { NSLog(@"%@",[[NSString alloc] initWithFormat:@"%i天%i小時%i分鐘",days,hours,minute]); // 之所以要 + 1,是因爲 此處的days 計算的結果 不包含當天 和 最後一天\ (如星期一 和 星期四,計算機 算的結果就是2天(星期二和星期三),日常算,星期一——星期四相差3天,所以需要+1)\ 對於時分 沒有進行計算 可以忽略不計 return days + 1; } } |
第三段代碼
1
2
3
4
5
6
7
8
9
10
11
12
|
// 獲取當前是星期幾
-
(NSInteger)getNowWeekday
{
NSCalendar
*calendar
=
[[NSCalendar
alloc]
initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents
*comps
=
[[NSDateComponents
alloc]
init];
NSInteger
unitFlags
=
NSYearCalendarUnit
|
NSMonthCalendarUnit
|
NSDayCalendarUnit
|
NSWeekdayCalendarUnit
|
NSHourCalendarUnit
|
NSMinuteCalendarUnit
|
NSSecondCalendarUnit;
NSDate
*now
=
[NSDate
date];
//
話說在真機上需要設置區域,才能正確獲取本地日期,天朝代碼:zh_CN
calendar.locale
=
[[NSLocale
alloc]
initWithLocaleIdentifier:@"zh_CN"];
comps
=
[calendar
components:unitFlags
fromDate:now];
return
[comps
weekday];
}
|