Sign in to follow this  
Followers 0
chakka

Calculating Nearest Sunday

17 posts in this topic

Hello all,

How to calculate the nearest Sunday?

  • 2012/12/30 (Previous Sunday)
  • 2013/01/03(Today)
  • 2013/01/06(Coming Sunday)
Here considering today's date(2013/01/03) the nearest Sunday is coming Sunday(2013/01/06)

How to achieve this using AutoIt? any function close to this?

Thanks

Share this post


Link to post
Share on other sites



chakka,

Are you saying that you want the next Sunday following any date? It may not be the "nearest", for example, if it is Monday the "nearest" Sunday is the previous Sunday.

kylomas


Forum Rules         Procedure for posting code

"I like pigs.  Dogs look up to us.  Cats look down on us.  Pigs treat us as equals."

- Sir Winston Churchill

Share this post


Link to post
Share on other sites

....for example, if it is Monday the "nearest" Sunday is the previous Sunday.

Yes exactly, and I'm looking the same.

If it's Monday then then nearest Sunday is previous Sunday(date?) and If it's Friday then nearest Sunday is coming Sunday(date?)

All I want to get is the date of that day.

Thanks kylomas, can you please provide rough example.

Share this post


Link to post
Share on other sites

Take a look at the _DateToDayOfWeek function. You should be able to use this to get the day of the week for a given date, and then you could adjust forwards or backwards depending on the returned value.

Share this post


Link to post
Share on other sites

chakka,

This will get you started

; get closest Sunday from whatever date this is run

#include <date.au3>

if @wday <= 4 then
    local $Sunday = _dateadd('D',-(7-@wday),_NowCalcDate())
    ConsoleWrite($Sunday & @LF)
Else
    local $Sunday = _dateadd('D',(7-@wday)+1,_NowCalcDate())
    ConsoleWrite($Sunday & @LF)
endif

kylomas

1 person likes this

Forum Rules         Procedure for posting code

"I like pigs.  Dogs look up to us.  Cats look down on us.  Pigs treat us as equals."

- Sir Winston Churchill

Share this post


Link to post
Share on other sites

#6 ·  Posted (edited)

Here a little example:

#include <date.au3>
#include <DateTimeConstants.au3>
#include <GUIConstantsEx.au3>


Opt('GUIOnEventMode', 1)

Global $sTitel = 'Nearest Sunday'

Local $hMainGui = GUICreate($sTitel, 400, 280, 140, 150)
GUISetOnEvent($GUI_EVENT_CLOSE, '_MyExit')
Global $idMnuHELP = GUICtrlCreateMenu("?", -1, 1)
GUICtrlCreateMenuItem("Autor: autoBert", $idMnuHELP)
GUICtrlCreateMenuItem("e&xit", $idMnuHELP)
GUICtrlSetOnEvent(-1, '_MyExit')

Local $idEdtDATE = GUICtrlCreateDate("01.01.2009", 20, 10, 150, 25, $DTS_UPDOWN)
Local $DTM_SETFORMAT_ = 0x1032
Local $style = "dd.MM.yyyy"
GUICtrlSendMsg($idEdtDATE, $DTM_SETFORMAT_, 0, $style)
GUICtrlSetFont(-1, 12)

GUICtrlCreateButton('&Check nearest Sunday', 220, 10, 150, 25)
GUICtrlSetOnEvent(-1, '_CheckDate')

Local $idLblRESULT = GUICtrlCreateLabel("", 12, 50, 200,25)
GUICtrlCreateButton('e&xit', 220, 115, 150, 25)
GUICtrlSetOnEvent(-1, '_MyExit')

GUISetState()

While 1
Sleep(120)
WEnd

Func _MyExit()
GUIDelete($hMainGui)
Exit
EndFunc ;==>_MyExit

Func _CheckDate()
Local $sCheckDate = GUICtrlRead($idEdtDATE), $sMsg
Local $iDay = StringLeft($sCheckDate,2)
Local $iMonth = StringMid($sCheckDate,4,2)
Local $iYear = StringRight($sCheckDate,4)
ConsoleWrite($sCheckDate&@CRLF)
Local $iDayOfWeek = _DateToDayOfWeekISO($iYear,$iMonth,$iDay)
Switch $iDayOfWeek
Case 7    ;<=
$sMsg = "Lol, today is a sunday!"
case 1,2,3
$sMsg = "The nearest sunday is " & _DateAdd("D",$iDayOfWeek*-1,$iYear&"/"&$iMonth&"/"&$iDay)
Case Else
$sMsg = "The nearest sunday is " & _DateAdd("D",7-$iDayOfWeek,$iYear&"/"&$iMonth&"/"&$iDay)
EndSwitch
GUICtrlSetData($idLblRESULT, $sMsg)
GUISetState()
EndFunc ;==>_CallEaster

Edit: Script correctedt, thanks to Malkey

Edited by AutoBert
1 person likes this

Share this post


Link to post
Share on other sites

#7 ·  Posted (edited)

Thanks kylomas. You solved it for me.

Edited by chakka

Share this post


Link to post
Share on other sites

Your Welcome! You'll find the Help file very useful for the rich compliment of date manipulation functions.


Forum Rules         Procedure for posting code

"I like pigs.  Dogs look up to us.  Cats look down on us.  Pigs treat us as equals."

- Sir Winston Churchill

Share this post


Link to post
Share on other sites

This example appears to be returning the results you are after in post #1.

; get closest Sunday to whatever date
#include <date.au3>
Local $sDate, $aDate, $sRet, $iDay
For $i = 1 To 14
    $sDate = "2013/01/" & StringRight("0" & $i, 2)
    ConsoleWrite($sDate & " ")
    $aDate = StringSplit($sDate, "/", 2)
    $iDay = _DateToDayOfWeek($aDate[0], $aDate[1], $aDate[2])
    ConsoleWrite(_DateDayOfWeek($iDay, 1) & "  ")
    Switch $iDay
        Case 1
            $sRet = $sDate & " (Today)"
        Case 2 To 4
            $sRet = _DateAdd("D", (1 - $iDay), $sDate) & " (Previous Sunday)"
        Case 5 To 7
            $sRet = _DateAdd("D", 8 - $iDay, $sDate) & " (Coming Sunday)"
    EndSwitch
    ConsoleWrite($sRet & @LF)
Next

#cs
Output @ console:-
2013/01/01 Tue  2012/12/30 (Previous Sunday)
2013/01/02 Wed  2012/12/30 (Previous Sunday)
2013/01/03 Thu  2013/01/06 (Coming Sunday)
2013/01/04 Fri  2013/01/06 (Coming Sunday)
2013/01/05 Sat  2013/01/06 (Coming Sunday)
2013/01/06 Sun  2013/01/06 (Today)
2013/01/07 Mon  2013/01/06 (Previous Sunday)
2013/01/08 Tue  2013/01/06 (Previous Sunday)
2013/01/09 Wed  2013/01/06 (Previous Sunday)
2013/01/10 Thu  2013/01/13 (Coming Sunday)
2013/01/11 Fri  2013/01/13 (Coming Sunday)
2013/01/12 Sat  2013/01/13 (Coming Sunday)
2013/01/13 Sun  2013/01/13 (Today)
2013/01/14 Mon  2013/01/13 (Previous Sunday)
#ce

@AutoBert

Your example is incorrectly calling 05/01/2013 a Sunday.

@kylomas

Your example works fine on the 2013/01/04.

Share this post


Link to post
Share on other sites

malkey, thanks, I tested it with various variable values before switching it back to the @wday macro


Forum Rules         Procedure for posting code

"I like pigs.  Dogs look up to us.  Cats look down on us.  Pigs treat us as equals."

- Sir Winston Churchill

Share this post


Link to post
Share on other sites

#11 ·  Posted (edited)

chakka,

After looking at malkey's code I realized that I had not accounted for runday = Sunday. Changed the code as follows

; get closest Sunday from whatever date this is run

#include <date.au3>

; added the following to account for runday = Sunday

if @wday = 1 then
    consolewrite(_nowcalcdate() & @lf)
    Exit
endif

if @wday <= 4 then
    local $Sunday = _dateadd('D',-(7-@wday),_NowCalcDate())
    ConsoleWrite($Sunday & @LF)
Else
    local $Sunday = _dateadd('D',(7-@wday)+1,_NowCalcDate())
    ConsoleWrite($Sunday & @LF)
endif

kylomas

Edited by kylomas

Forum Rules         Procedure for posting code

"I like pigs.  Dogs look up to us.  Cats look down on us.  Pigs treat us as equals."

- Sir Winston Churchill

Share this post


Link to post
Share on other sites

This is better (adapting malkey's technique)

; get closest Sunday from whatever date this is run

#include <date.au3>

ConsoleWrite(_ClosestSunday() & @lf)

func _ClosestSunday()

    switch @WDAY
        case 1
            return _nowcalcdate()
        case 2 to 4
            return _dateadd('D',-(7-@wday),_NowCalcDate())
        case 5 to 7
            return _dateadd('D',(7-@wday)+1,_NowCalcDate())
    endswitch

endfunc

kylomas


Forum Rules         Procedure for posting code

"I like pigs.  Dogs look up to us.  Cats look down on us.  Pigs treat us as equals."

- Sir Winston Churchill

Share this post


Link to post
Share on other sites

Nice functions people.

Just an observation, but it's best to declare variables 'outside of blocks.'

Local $fVar
If True Then
    $fVar = True
Else
    $fVar = False
EndIf

_AdapterConnections()_AlwaysRun()_AppMon()_AppMonEx()_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: 04/09/2015

Share this post


Link to post
Share on other sites

#14 ·  Posted (edited)

Here another method:

#include <Date.au3>
ConsoleWrite(NearestSunday("2013/01/01") & @LF)
ConsoleWrite(NearestSunday("2013/01/09") & @LF)
ConsoleWrite(NearestSunday("2013/01/20") & @LF)
ConsoleWrite(NearestSunday("2013/01/31") & @LF)


Func NearestSunday($sDate) ;format YYYY/MM/DD
    Local $aDate = StringSplit($sDate, "/", 2)
    Local $iD = _DateToDayOfWeek($aDate[0], $aDate[1], $aDate[2])
    Switch $iD
        Case 2 To 4
            Return _DateAdd("d", -$iD + 1, $sDate)
        Case 5 To 7
            Return _DateAdd("d", -$iD + 8, $sDate)
        Case Else
            Return $sDate
    EndSwitch
EndFunc

Edit: ok, it is very close to Malkey's version... :whistle:

Br,

UEZ

Edited by UEZ

Please don't send me any personal message and ask for support! I will not reply!

Selection of finest graphical examples at Codepen.io

The own fart smells best!
Her 'sikim hıyar' diyene bir avuç tuz alıp koşma!
¯\_(ツ)_/¯  ٩(●̮̮̃•̃)۶ ٩(-̮̮̃-̃)۶ૐ

Share this post


Link to post
Share on other sites

And before someone beats me to it...

The one-line version:

#include <date.au3>
MsgBox(0,"",_dateadd('D',-(@WDAY - 1 + (@WDAY > 4) * -7),_NowCalcDate()))

Share this post


Link to post
Share on other sites

@ kylomas, UEZ, Spiff59

Instead of _NowCalcDate() in each of your examples, I used "2013/01/07". The closest Sunday, "2013/01/06", was not returned.

Share this post


Link to post
Share on other sites

Thanks for the bug hint Malkey! Modified the version, should work now...

Br,

UEZ


Please don't send me any personal message and ask for support! I will not reply!

Selection of finest graphical examples at Codepen.io

The own fart smells best!
Her 'sikim hıyar' diyene bir avuç tuz alıp koşma!
¯\_(ツ)_/¯  ٩(●̮̮̃•̃)۶ ٩(-̮̮̃-̃)۶ૐ

Share this post


Link to post
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
Sign in to follow this  
Followers 0

  • Similar Content

    • Mark917
      By Mark917
      I am trying to extract a date and time from a website using InetRead.  The source for the page I am reading shows the date and time as shown below.  I need to somehow extract the correct date and time from this information.  Is there a function or calculation that will do this?  The source shown here correlates to 15:20 (time) 29.03.17 (date).
      <div class="cell game-date" data-time="1490818800000"> <div class="site__time" data-time="1490818800000"> <div class="time"></div> <div class="date"></div> </div> </div>  
    • ces1a
      By ces1a
      This is an easy way to get the number of days between today and any future date without having to acount for Hours, Minutes, and Seconds.
      #include <Date.au3>
      Func ShowDays($FutureDate)
          $iDaysDiff = _DateDiff('D', _NowCalcDate(), $FutureDate)
          If $iDaysDiff < 1 Then Return 0 ;Insure only positive return
          Return $iDaysDiff
      EndFunc ;==GoPR
      MsgBox(0, '',  ShowDays("2017/07/31"))
      I use it to know how many days till I go on my next vacation.
      Maybe one of you can find a use for it.
    • gritts
      By gritts
      I searched for this oddity for a while but found no results. If I missed it, my apologies.
      I have an app that I am building that will eventually search a SQL database for results within a specified range of time. To collect the range of time required but the user, I have 2 fields I created, one for start and the other for end times. They are formatted "yyyy/MM/dd HH:MM:ss" for entry.
      The fields are created with this:
      $dpStartDate = GUICtrlCreateDate(_NowCalc(), 112, 88, 146, 24) $dpEndDate = GUICtrlCreateDate(_NowCalc(), 416, 88, 146, 24) I am setting the format of the fields with this code: $DTM_SETFORMAT_ = 0x1032 ; $DTM_SETFORMATW $style = "yyyy/MM/dd hh:mm:ss" GUICtrlSendMsg($dpStartDate, $DTM_SETFORMAT_, 0, $style) GUICtrlSendMsg($dpEndDate, $DTM_SETFORMAT_, 0, $style) What I am attempting to do is when the start field is updated, compare it with the end time field. If the end time is less than the start time, make both fields match. When I attempt to do so with the function below, The end time date is copied correctly but the time (hour) is reset to 1, no matter the time entered. Am I going about updating the field incorrectly?
      As an example, I set the date in the start field to "2013/08/23 11:47:38", the end time field gets set to "2013/08/23 01:00:00"
      Func dpStartDateChange() Local $stDT = GUICtrlRead($dpStartDate), $edDT = GUICtrlRead($dpEndDate) If $edDT < $stDT Then MsgBox(0,"Change Needed","End Time: "&$edDT&@CRLF&"Start Time: "&$stDT) ;Shows correct time GUICtrlSetData($dpEndDate,$stDT) EndIf EndFunc There is no code for SQL in place yet. I am working on some of the GUI logic for now. Let me know if there is enough code here or you need more.