ajg724
ajg724

Reputation: 17

Check if date is within a given timeframe

I need to check if a date falls within a certain range.

I suppose I need the function to look something like this:

If Date.Now.ToString("dd/MM/yyyy") - 2 days <= sc3 <= Date.Now.ToString("dd/MM/yyyy") Then
     sc3 = D
     Console.WriteLine(D)
End If

However, I don't actually know what to put for the first part (Date.Now.ToString("dd/MM/yyyy") - 2 days).

Basically I need to check if a date falls between the current date and 2 days before.

Upvotes: 0

Views: 2621

Answers (3)

srka
srka

Reputation: 802

If Date.Now.AddDays(-2)<=sc3 AndAlso sc3<=Date.Now Then
    sc3 = D
    Console.WriteLine(D)
End If

Upvotes: 0

tcarvin
tcarvin

Reputation: 10855

Your code sample is VB.NET.

Ignoring time, this would be something like this:

Dim testDate As DateTime = new DateTime(2014, 1,1)
Dim currDate As DateTime = DateTime.Now.Date

If testDate <= currDate AndAlso testDate >= currDate - TimeSpan.FromDays(2) Then

'within range

End If 

I didn't syntax check this, but it should get you started.

Upvotes: 2

Ekkehard.Horner
Ekkehard.Horner

Reputation: 38745

Use the docs for DateAdd and DateDiff to understand/experiment with:

Option Explicit

Dim dtToday : dtToday = Date
Dim nDiff
For nDiff = -3 To +3
    Dim dtTest : dtTest = DateAdd("d", nDiff, dtToday)
    Dim nDiff2 : nDiff2 = DateDiff("d", dtToday, dtTest)
    Dim bInR   : bInR   = -2 <= nDiff2 And 0 >= nDiff2 ' depends on your understand of "berween"
    WScript.Echo nDiff, dtTest, CStr(bInR)
Next

output:

-3 05.01.2014 False
-2 06.01.2014 True
-1 07.01.2014 True
0 08.01.2014 True
1 09.01.2014 False
2 10.01.2014 False
3 11.01.2014 False

(I choose to believe your VBScript tag)

Upvotes: 3

Related Questions