Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if date falls between 2 dates

Tags:

swift

I have this code where convert a String into a date object

let date2 = KeysData[indexPath.row]["starttime"] as? String  let dateFormatter = NSDateFormatter() dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"  if let date = dateFormatter.dateFromString(date2!) {    println(date)           } 

I would like to know if the current date falls between the 2 days i got in the array startdate and endate

like image 383
Exceptions Avatar asked Sep 30 '15 06:09

Exceptions


People also ask

Is a date between two dates Excel?

To find the number of days between these two dates, you can enter “=B2-B1” (without the quotes into cell B3). Once you hit enter, Excel will automatically calculate the number of days between the two dates entered.

How do you find if a date is between two dates in JavaScript?

To check if one date is between two dates with JavaScript, we can compare their timestamps. const currentDate = new Date(). toJSON(). slice(0, 10); const from = new Date("2022/01/01"); const to = new Date("2022/01/31"); const check = new Date(currentDate); console.

How do you Vlookup a date range?

To retrieve a value on a specific date from a table, you can use the VLOOKUP function. This is a standard VLOOKUP formula. It requires a table with lookup values (in this case, dates) to the left of the values being retrieved. The lookup value comes from cell E6, which must be a valid date.


1 Answers

Swift ≧ 3

Swift 3 makes this a lot easier.

let fallsBetween = (startDate ... endDate).contains(Date()) 

Now that NSDate is bridged to the value type Date and Date conforms to Comparable we can just form a ClosedRange<Date> and use the contains method to see if the current date is included.

Caveat: endDate must be greater or equal startDate. Otherwise the range could not be formed and the code would crash with a fatalError.

This is safe:

extension Date {     func isBetween(_ date1: Date, and date2: Date) -> Bool {         return (min(date1, date2) ... max(date1, date2)).contains(self)     } } 
like image 159
Nikolai Ruhe Avatar answered Oct 03 '22 09:10

Nikolai Ruhe