iOS Question why does this code make my app crash??

ilan

Expert
Licensed User
Longtime User
something is not clear to me

i want to check if a specific February is a leap year with this piece of code:

B4X:
Sub IsLeapYear(Year As Int) As Boolean
   Try
      DateTime.DateFormat = "MM/dd/yyyy"
      DateTime.DateParse("02/29/" & Year)
      Return True
   Catch
      Log(LastException)
      Return False
   End Try
End Sub

so if the try wont be able to parse the date the catch should be raised and i should get a false returned
but i am getting an error and a crash that says could not parse the date.


but why does this code crash? i am using a try catch..

any clue?

regards, ilan
 

ilan

Expert
Licensed User
Longtime User
ok i understand what was the problem. i grabbed this code from the forum and it uses a different Date.Format then i use in the Callback Sub.

changing the Date.Format to "dd/MM/yyyy" solved the problem
 
Upvote 0

Ed Brown

Active Member
Licensed User
Longtime User
Hi @ilan

This will give you a true/false answer:
B4X:
isLeap = (((y mod 4) = 0) And ((y mod 100) <> 0)) Or ((y mod 400) = 0)

used like...
B4X:
DateTime.DateFormat = "dd/MM/yyyy"
Dim ldate As Long = DateTime.DateParse("31/3/1901")

Dim y = DateTime.GetYear(ldate)        ' Get the year
Dim isLeap As Boolean
isLeap = (((y mod 4) = 0) And ((y mod 100) <> 0)) Or ((y mod 400) = 0)

Log(isLeap)

Leap years are every 4 years except for centuries (ie. 1700,1800,1900). Every 400 years the century IS a leap year (ie. 1600, 2000, 2400).

Hope this helps.
 
Upvote 0
Cookies are required to use this site. You must accept them to continue using the site. Learn more…