Unexpected result in determining day of week

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By Sylkie

Working at getting a proper calendar class going. I downloaded the popup calendar control by Ivan Skodje but it has issues with the current version of GDScript.
Apparently, after it was written, some boolean operations were disallowed and it now throws an error. The get Weekday function uses this syntax to get the day of the week from a date:

  y -= m < 3

where y is year, and m is month as integers.

I have changed that to a simple if statement:

  if m < 3: int(y - m)

That fixes it, and the code does indeed run, and returns (mostly) expected results.

mostly…

February 1, 2019 returns a day 1 less than the expected date.

Original code in the button script from Ivan Skodje is:

func get_weekday(d, m, y):

 # Returns the weekday (int)
    var t = [0, 3, 2, 5, 0, 3, 5, 1, 4, 6, 2, 4]
    y -= m < 3
    return (y + y/4 - y/100 + y/400 + t[m-1] + d) % 7

My code to address the lack of boolean operators:

func get_beginning_weekday(y, m, d=1):
    
    # This gives a value of 1 less for February
    var t = [0, 3, 2, 5, 0, 3, 5, 1, 4, 6, 2, 4]
    if m < 3: y = int(y - m)
    return (y + int(y/4) - int(y/100) + int(y/400) + t[m-1] + d) % 7

( I default the day to 1 so that if I pass the function only a year and a month, I get the beginning day of the month)

I have tried both with, and without, casting the int’s.

However, for February 1, 2019 I get back a 4 (Thursday) instead of a 5 (Friday)

This algorithm is very well documented and explained on the web with many good examples in various languages. But I just cannot determine why I’m getting this functional error.

:bust_in_silhouette: Reply From: Holm

Based on the original code from Ivan Skodje:

   func get_weekday(d, m, y):

 # Returns the weekday (int)
    var t = [0, 3, 2, 5, 0, 3, 5, 1, 4, 6, 2, 4]
    y -= m < 3
    return (y + y/4 - y/100 + y/400 + t[m-1] + d) % 7

y -= m < 3 means two results:
if m less than 3 then is the result from (m < 3) always 1 (or true) and the calculation is: y -= 1
if m not less than 3 is the result from (m < 3) always 0 (or false) and the calculation is: y -= 0

The result from a condition is always 0 (false) or 1 (true).

But you calculate y = y - m if (m < 3) is true…

Hope this helps a bit.

you can code like this:

if m < 3: y -= 1

Holm | 2019-08-22 16:29

I did not truly understand the original code as two results. Your description makes absolute sense, and now I know. Thank you.

Sylkie | 2019-08-22 17:56