Jump to content

_IsBetweenDates()


spudw2k
 Share

Recommended Posts

I am working on a simple file filter tool based on a date range. I made this to help things along and thought I'd share it.

Code missing non YYYYMMDD format exception handling

#include <Date.au3>

;Is My Birthdate in 2013?
$var = _IsBetweenDates("1983/01/17","2013/01/01","2013/12/31")
msgbox(0,"_IsBetweenDates",$var & @CRLF & "err:" & @error)

;Is Today in the year 2013?
$var = _IsBetweenDates(@YEAR & "/" & @MON & "/" & @MDAY,"2013/01/01","2013/12/31")
msgbox(0,"_IsBetweenDates",$var & @CRLF & "err:" & @error)

;Is Today in the year 2013? (Reversed Start and End Test)
$var = _IsBetweenDates(@YEAR & "/" & @MON & "/" & @MDAY,"2013/12/31","2013/01/01")
msgbox(0,"_IsBetweenDates",$var & @CRLF & "err:" & @error)



; #FUNCTION# ====================================================================================================================
; Name...........: _IsBetweenDates
; Description ...: Determine if a given date is between two dates
; Syntax.........: _IsBetweenDates($ChosenDate,$StartDate,$EndDate)
; Parameters ....: $ChosenDate - YYYYMMDD format date to determine if within date range
; : $StartDate - YYYYMMDD format start date of date range
; : $EndDate - YYYYMMDD format end date of date range
; Return values .: Success - True
;            : Failure - False, sets @error to:
;            : |1 - Range must be at leat one day.
;            : |2 - Outside of Range - Lower
;            : |3 - Outside of Range - Higher
; Author ........: Spudw2k
; Modified.......:
; Remarks .......:
; Related .......:
; Link ..........:
; Example .......: Yes
; ===============================================================================================================================
Func _IsBetweenDates($ChosenDate,$StartDate,$EndDate)
Local $varDate1, $varDate2

;Verify Date Range is at least one day else error (1)
$varDate1 = _DateDiff('D',$StartDate,$EndDate)
If $varDate1 = 0 Then Return SetError(1,0,False)

;Enforce Start Date to be Before End Date
If $varDate1 < 0 Then
$varDate2 = $StartDate
$StartDate = $EndDate
$EndDate = $varDate2
EndIf

;Determine if desired date is within range
$varDate1 = _DateDiff('D',$StartDate,$ChosenDate)
If ($varDate1 < 0) Then Return SetError(2,0,False) ;Date is below range
$varDate2 = _DateDiff('D',$EndDate, $ChosenDate)
If ($varDate2 > 0) Then Return SetError(3,0,False) ;Date is above range
Return True ;Date is within range
EndFunc
Edited by spudw2k
Link to comment
Share on other sites

Nice example. Thanks.

UDF List:

 
_AdapterConnections()_AlwaysRun()_AppMon()_AppMonEx()_ArrayFilter/_ArrayReduce_BinaryBin()_CheckMsgBox()_CmdLineRaw()_ContextMenu()_ConvertLHWebColor()/_ConvertSHWebColor()_DesktopDimensions()_DisplayPassword()_DotNet_Load()/_DotNet_Unload()_Fibonacci()_FileCompare()_FileCompareContents()_FileNameByHandle()_FilePrefix/SRE()_FindInFile()_GetBackgroundColor()/_SetBackgroundColor()_GetConrolID()_GetCtrlClass()_GetDirectoryFormat()_GetDriveMediaType()_GetFilename()/_GetFilenameExt()_GetHardwareID()_GetIP()_GetIP_Country()_GetOSLanguage()_GetSavedSource()_GetStringSize()_GetSystemPaths()_GetURLImage()_GIFImage()_GoogleWeather()_GUICtrlCreateGroup()_GUICtrlListBox_CreateArray()_GUICtrlListView_CreateArray()_GUICtrlListView_SaveCSV()_GUICtrlListView_SaveHTML()_GUICtrlListView_SaveTxt()_GUICtrlListView_SaveXML()_GUICtrlMenu_Recent()_GUICtrlMenu_SetItemImage()_GUICtrlTreeView_CreateArray()_GUIDisable()_GUIImageList_SetIconFromHandle()_GUIRegisterMsg()_GUISetIcon()_Icon_Clear()/_Icon_Set()_IdleTime()_InetGet()_InetGetGUI()_InetGetProgress()_IPDetails()_IsFileOlder()_IsGUID()_IsHex()_IsPalindrome()_IsRegKey()_IsStringRegExp()_IsSystemDrive()_IsUPX()_IsValidType()_IsWebColor()_Language()_Log()_MicrosoftInternetConnectivity()_MSDNDataType()_PathFull/GetRelative/Split()_PathSplitEx()_PrintFromArray()_ProgressSetMarquee()_ReDim()_RockPaperScissors()/_RockPaperScissorsLizardSpock()_ScrollingCredits_SelfDelete()_SelfRename()_SelfUpdate()_SendTo()_ShellAll()_ShellFile()_ShellFolder()_SingletonHWID()_SingletonPID()_Startup()_StringCompact()_StringIsValid()_StringRegExpMetaCharacters()_StringReplaceWholeWord()_StringStripChars()_Temperature()_TrialPeriod()_UKToUSDate()/_USToUKDate()_WinAPI_Create_CTL_CODE()_WinAPI_CreateGUID()_WMIDateStringToDate()/_DateToWMIDateString()Au3 script parsingAutoIt SearchAutoIt3 PortableAutoIt3WrapperToPragmaAutoItWinGetTitle()/AutoItWinSetTitle()CodingDirToHTML5FileInstallrFileReadLastChars()GeoIP databaseGUI - Only Close ButtonGUI ExamplesGUICtrlDeleteImage()GUICtrlGetBkColor()GUICtrlGetStyle()GUIEventsGUIGetBkColor()Int_Parse() & Int_TryParse()IsISBN()LockFile()Mapping CtrlIDsOOP in AutoItParseHeadersToSciTE()PasswordValidPasteBinPosts Per DayPreExpandProtect GlobalsQueue()Resource UpdateResourcesExSciTE JumpSettings INISHELLHOOKShunting-YardSignature CreatorStack()Stopwatch()StringAddLF()/StringStripLF()StringEOLToCRLF()VSCROLLWM_COPYDATAMore Examples...

Updated: 22/04/2018

Link to comment
Share on other sites

faster

#include <Date.au3>

$Test = '2011.03.11.00.00.00'
; $Test = '2012.03.12.00.00.00'
; $Test = '2032.03.12.00.00.00'
$Test = StringRegExp($Test, '(\d+)', 3)

$Old = '2011.03.10.00.00.00'
$Old = StringRegExp($Old, '(\d+)', 3)

$New = _NowCalc()
$New = StringRegExp($New, '(\d+)', 3)

$var = ''
$timer = TimerInit()
For $i = 1 To 100
    $var &= _IsBetweenDates($Test, $Old, $New) & '|'
Next
MsgBox(0, "Result", 'Time : ' & Round(TimerDiff($timer), 2) & ' msec' & @CRLF & $var)

Func _IsBetweenDates($avCurDate, $asDate1, $asDate2)
    If Not IsArray($avCurDate) Or UBound($avCurDate) < 6 Then SetError(1, 0, '')
    If Not IsArray($asDate1) Or UBound($asDate1) < 6 Then SetError(2, 0, '')
    If Not IsArray($asDate2) Or UBound($asDate2) < 6 Then SetError(3, 0, '')
    For $i = 0 To 5
        $avCurDate[$i] = Number($avCurDate[$i])
    Next
    Local $iCount = 0
    $iCount += __CompareDates($avCurDate, $asDate1)
    If $iCount = 0 Then Return True
    $iCount += __CompareDates($avCurDate, $asDate2)
    Return ($iCount = 0)
EndFunc

Func __CompareDates(ByRef Const $aiOld, ByRef Const $asNew)
    Local $iCompare = 0
    For $i = 0 To 5
        If $asNew[$i] > $aiOld[$i] Then
            $iCompare += 1
            ExitLoop
        ElseIf $asNew[$i] < $aiOld[$i] Then
            $iCompare -= 1
            ExitLoop
        Else
            ContinueLoop
        EndIf
    Next
    Return $iCompare
EndFunc
Edited by AZJIO
Link to comment
Share on other sites

faster

Much faster...though a bit harder for me to get my head around at first. I've never considered a purely calculative approach when working with dates, but I suppose that a YYYYMMDD value should be easy to compare with another. Thanks. Edited by spudw2k
Link to comment
Share on other sites

I do it like this:

Func _DateBetween($sDate, $sBegin, $sEnd)
    $sDate= StringReplace($sDate, ":", "")
    $sDate= StringReplace($sDate, "/", "")
    $sDate= StringReplace($sDate, " ", "")
    $sBegin = StringReplace($sBegin, ":", "")
    $sBegin = StringReplace($sBegin, "/", "")
    $sBegin = StringReplace($sBegin, " ", "")
    $sEnd= StringReplace($sEnd, ":", "")
    $sEnd= StringReplace($sEnd, "/", "")
    $sEnd= StringReplace($sEnd, " ", "")
   
    If Int($sDate) >= Int($sBegin) And Int($sDate) <= Int($sEnd) Then Return 1
    Return 0
EndFunc
Link to comment
Share on other sites

A lot of unnecessary StringReplace functions there, when you can do it with SRE.

UDF List:

 
_AdapterConnections()_AlwaysRun()_AppMon()_AppMonEx()_ArrayFilter/_ArrayReduce_BinaryBin()_CheckMsgBox()_CmdLineRaw()_ContextMenu()_ConvertLHWebColor()/_ConvertSHWebColor()_DesktopDimensions()_DisplayPassword()_DotNet_Load()/_DotNet_Unload()_Fibonacci()_FileCompare()_FileCompareContents()_FileNameByHandle()_FilePrefix/SRE()_FindInFile()_GetBackgroundColor()/_SetBackgroundColor()_GetConrolID()_GetCtrlClass()_GetDirectoryFormat()_GetDriveMediaType()_GetFilename()/_GetFilenameExt()_GetHardwareID()_GetIP()_GetIP_Country()_GetOSLanguage()_GetSavedSource()_GetStringSize()_GetSystemPaths()_GetURLImage()_GIFImage()_GoogleWeather()_GUICtrlCreateGroup()_GUICtrlListBox_CreateArray()_GUICtrlListView_CreateArray()_GUICtrlListView_SaveCSV()_GUICtrlListView_SaveHTML()_GUICtrlListView_SaveTxt()_GUICtrlListView_SaveXML()_GUICtrlMenu_Recent()_GUICtrlMenu_SetItemImage()_GUICtrlTreeView_CreateArray()_GUIDisable()_GUIImageList_SetIconFromHandle()_GUIRegisterMsg()_GUISetIcon()_Icon_Clear()/_Icon_Set()_IdleTime()_InetGet()_InetGetGUI()_InetGetProgress()_IPDetails()_IsFileOlder()_IsGUID()_IsHex()_IsPalindrome()_IsRegKey()_IsStringRegExp()_IsSystemDrive()_IsUPX()_IsValidType()_IsWebColor()_Language()_Log()_MicrosoftInternetConnectivity()_MSDNDataType()_PathFull/GetRelative/Split()_PathSplitEx()_PrintFromArray()_ProgressSetMarquee()_ReDim()_RockPaperScissors()/_RockPaperScissorsLizardSpock()_ScrollingCredits_SelfDelete()_SelfRename()_SelfUpdate()_SendTo()_ShellAll()_ShellFile()_ShellFolder()_SingletonHWID()_SingletonPID()_Startup()_StringCompact()_StringIsValid()_StringRegExpMetaCharacters()_StringReplaceWholeWord()_StringStripChars()_Temperature()_TrialPeriod()_UKToUSDate()/_USToUKDate()_WinAPI_Create_CTL_CODE()_WinAPI_CreateGUID()_WMIDateStringToDate()/_DateToWMIDateString()Au3 script parsingAutoIt SearchAutoIt3 PortableAutoIt3WrapperToPragmaAutoItWinGetTitle()/AutoItWinSetTitle()CodingDirToHTML5FileInstallrFileReadLastChars()GeoIP databaseGUI - Only Close ButtonGUI ExamplesGUICtrlDeleteImage()GUICtrlGetBkColor()GUICtrlGetStyle()GUIEventsGUIGetBkColor()Int_Parse() & Int_TryParse()IsISBN()LockFile()Mapping CtrlIDsOOP in AutoItParseHeadersToSciTE()PasswordValidPasteBinPosts Per DayPreExpandProtect GlobalsQueue()Resource UpdateResourcesExSciTE JumpSettings INISHELLHOOKShunting-YardSignature CreatorStack()Stopwatch()StringAddLF()/StringStripLF()StringEOLToCRLF()VSCROLLWM_COPYDATAMore Examples...

Updated: 22/04/2018

Link to comment
Share on other sites

matwachich

You need to check that the old date is really old

; #include <Date.au3>

$Test = '2002.03.11.00.00.00'
; $Test = '2012.03.12.00.00.00'
; $Test = '2032.03.12.00.00.00'
$Test = StringRegExpReplace($Test, '\D+', '')

$Old = '2011.03.10.00.00.00'
$Old = StringRegExpReplace($Old, '\D+', '')

; $New = _NowCalc()
$New = '2013.04.01.00.00.00'
$New = StringRegExpReplace($New, '\D+', '')

$var = ''
$timer = TimerInit()
For $i = 1 To 100
    $var &= _IsBetweenDates($Test, $Old, $New) & '|'
Next
MsgBox(0, "Result", 'Time : ' & Round(TimerDiff($timer), 2) & ' msec' & @CRLF & $var)

Func _IsBetweenDates($sCurDate, $Old, $New)
    $Old = Number($Old)
    If $Old > $New Then
        Local $tmp = $New
        $New = $Old
        $Old = $tmp
    EndIf
    $sCurDate = Number($sCurDate)
    If $sCurDate >= $Old And $sCurDate <= $New Then
        Return True
    Else
        Return False
    EndIf
EndFunc

#include <Date.au3>
#include <File.au3>
#include <GUIConstantsEx.au3>
#Include <GuiListView.au3>

$Old = '2001.03.10.00.00.00'
$Old = StringRegExpReplace($Old, '\D+', '')

; $New = _NowCalc()
$New = '2011.04.01.00.00.00'
$New = StringRegExpReplace($New, '\D+', '')

$aFiles = _FileListToArray (@SystemDir, "*.*", 1)

$hGui = GUICreate ("FileTime")
$ListView = GUICtrlCreateListView ("File|Time", 5, 5, 390, 390)
_GUICtrlListView_SetColumnWidth ($ListView, 0, 230)
_GUICtrlListView_SetColumnWidth ($ListView, 1, 70)
GUISetState()

; $timer = TimerInit()
For $i = 1 To $aFiles[0]
    $aFileTime = FileGetTime(@SystemDir & "\" & $aFiles[$i], 1, 1)
    If _IsBetweenDates($aFileTime, $Old, $New) Then GUICtrlCreateListViewItem ($aFiles[$i] & "|" & $aFileTime, $ListView)
Next
; WinSetTitle($hGui, '', "FileTime, Time = " & Round(TimerDiff($timer), 2) & ' msec')

Do
Until GUIGetMsg() = $GUI_EVENT_CLOSE

Func _IsBetweenDates($sCurDate, $Old, $New)
    $Old = Number($Old)
    If $Old > $New Then
        Local $tmp = $New
        $New = $Old
        $Old = $tmp
    EndIf
    $sCurDate = Number($sCurDate)
    If $sCurDate >= $Old And $sCurDate <= $New Then
        Return True
    Else
        Return False
    EndIf
EndFunc
Edited by AZJIO
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...