Here's a little ditty that'll show you a few concepts in practice. Though not best practice, as inputs are not sanitized - I'll leave that to you
/* ************************************** *
* *
* Fun little days since birth calculator *
* *
* CC-BY Roy Dybing *
* April 2018 *
* *
* May be a day off with certain dates... *
* *
* ************************************** */
SetErrorMode(2)
SetWindowTitle("ageToDays")
SetWindowSize(1024, 768, 0)
SetWindowAllowResize(1)
SetVirtualResolution(1024, 768)
SetOrientationAllowed(1, 1, 1, 1)
SetSyncRate(30, 0)
SetScissor(0,0,0,0)
UseNewDefaultFonts(1)
#constant false = 0
#constant true = 1
type date_t
year as integer
month as integer
day as integer
endType
main()
function main()
birth as date_t
today as date_t
days as integer
repeat
birth = bornDate()
today = todayDate()
days = numberDays(birth, today)
repeat
quit = GetRawKeyPressed(27)
again = GetRawKeyPressed(32)
print(str(birth.year) + ":" + str(birth.month) + ":" + str(birth.day))
print(str(today.year) + ":" + str(today.month) + ":" + str(today.day))
print("Days: " + str(days))
print("Hit space to enter a new date, hit escape to quit")
sync()
until again or quit
until quit
endFunction
function bornDate()
in as string[2]
out as date_t
text as string[2] = ["What year were you born?", "What month were you born? (1-12)", "...and what day (1-31)"]
for i = 0 to text.length
StartTextInput("")
repeat
print(text[i])
sync()
until GetTextInputCompleted()
in[i] = GetTextInput()
StopTextInput()
next i
out.year = val(in[0])
out.month = val(in[1])
out.day = val(in[2])
endFunction out
function todayDate()
out as date_t
today as string
today = GetCurrentDate()
out.year = val(GetStringToken(today, "-", 1))
out.month = val(GetStringToken(today, "-", 2))
out.day = val(GetStringToken(today, "-", 3))
endFunction out
function numberDays(born as date_t, today as date_t)
days as integer
monthDays as integer[11] = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
for i = born.year to today.year - 1
days = days + 365
if isLeapYear(i)
inc days
endif
next i
if born.month > today.month
days = days - 365
for i = born.month to 12
days = days + monthDays[i - 1]
next i
for i = 1 to today.month - 1
days = days + monthDays[i - 1]
next i
else
for i = born.month to today.month - 1
days = days + monthDays[i - 1]
next i
endif
if born.day > today.day
days = days - monthDays[born.month]
for i = born.day to monthDays[born.month]
inc days
next i
for i = 1 to today.day - 1
inc days
next i
else
for i = born.day to today.day - 1
inc days
next i
endif
endFunction days
function isLeapYear(year)
leapYear as integer = false
if mod(year, 400) = 0
leapYear = true
elseif mod(year, 100) = 0
leapYear = false
elseif mod(year, 4) = 0
leapYear = true
endif
endFunction leapYear
Got any questions on how it all works, do ask.