iOS判斷乙個日期是否為昨日 今日 今年

2021-07-16 04:13:08 字數 1513 閱讀 4557

1、需要建立乙個nsdate類的category,呼叫的時候需要傳進來乙個nsdate型別的時間即可返回bool值來判斷改時間是不是今日等。

2、直接上乾貨

建立完分類後,在.h檔案中加入下面的**:

#import

@inte***ce

nsdate (extension)

/*** 

是否為今天 */

- (bool

)istoday;

/*** 

是否為昨天 */

- (bool

)isyesterday;

/*** 

是否為今年 */

- (bool

)isthisyear;

/*** 

返回乙個只有年月日的時間 */

- (nsdate

*)datewithymd;

/*** 

獲得與當前時間的差距 */

- (nsdatecomponents

*)deltawithnow;

@end

3、切換到.m檔案中,加入下面**:

#import

"nsdate+extension.h"

@implementation

nsdate (extension)

/*** 

是否為今天 */

- (bool

)istoday

/**

*  是否為昨天 */

- (bool

)isyesterday

/**

*  是否為今年 */

- (bool

)isthisyear

/**

*  返回乙個只有年月日的時間 */

- (nsdate

*)datewithymd

/**

*  獲得與當前時間的差距 */

- (nsdatecomponents

*)deltawithnow

@end

4、使用該方法:

nsdateformatter

*formater = [[

nsdateformatter

alloc

] init];

formater.

dateformat

= @"yyyy-mm-dd hh:mm:ss";

nsdate

*senddate  = [formater

datefromstring

:@"你想判斷的時間"

];     senddate

.istoday  //判斷是否為今日

senddate

.isthisyear //判斷是否為昨日

senddate

.isyesterday  //判斷是否為今年

還有乙個是獲取與當前時間差距的方法deltawithnow

基本上就是這樣搞的

判斷乙個日期輸入是否正確。

本程式用於驗證輸入從公元元年後的乙個日期,然後判斷日期是否正確。若輸入錯誤日期,則繼續進行此流程,直至日期正確。rq函式中先對月份和年份進行判斷,然後在switch中對二月做閏年的處理,判斷其是否正確。include int rq int y,int m,int d if year 1 switch...

判斷乙個整數是否為偶數

python3.7 輸入乙個整數,判斷其是否為偶數 print 判斷乙個數是否為偶數 number input 請輸入乙個整數 time 1 while time 1 while not number.isdigit print 這不是乙個整數,請重新輸入 end number input numb...

判斷乙個變數是否為陣列

1 var array new array 1 2 3 4 5 console.log array instanceof array true 2 var array new array 1 2 3 4 5 console.log array.constructor array true 3 fun...