Is It A Leap Year? Delphi and C++Builder VCL Apps
Happy New Year 2016! And yes, 2016 is a leap year, so we all have an additional day for programming this year. Here are two VCL applications, one written using Delphi and one written using C++Builder. The projects have a simple VCL form (you can do the same using FireMonkey) with a TButton, a TDateTimePicker and a TShape. I want to color the shape red if the selected date in the calendar is not in a leap year and color the shape green if it the date is in a leap year. Most every developer knows the rules for determining whether a year is a leap year or not (at least for those of you who use the Gregorian calendar).
As a reminder, here are the Gregorian calendar rules for a leap year. In the Gregorian calendar there are 3 criteria for identifying a leap year.
- The year is divisible by 4
- If the year can be divided by 100, it is NOT a leap year, unless...
- The year is also divisible by 400, then it is a leap year.
Note: The years 2000, 2400, 2800 and so on are examples of using the 3rd criteria above.
Here are screen shots of my VCL forms in the RAD Studio 10 Seattle IDE
I have used 3 event handlers in each application: the Form's OnCreate, the Button's OnClick and the TDateTimePicker's OnChange (re-uses the Button's OnClick handler). Here is the source code for Delphi and C++Builder. To determine if the year selected is a leap year, I use the IsLeapYear function that is defined in the DateUtils run time library unit.
uses System.DateUtils; procedure TForm1.Button1Click(Sender: TObject); begin if IsLeapYear(YearOf(DateTimePicker1.Date)) then Shape1.Brush.Color := clGreen else Shape1.Brush.Color := clRed end; procedure TForm1.FormCreate(Sender: TObject); begin DateTimePicker1.Date := Now(); end;
#include <System.DateUtils.hpp> void __fastcall TForm2::Button1Click(TObject *Sender) { if (IsLeapYear(YearOf(DateTimePicker1->Date))) { Shape1->Brush->Color = clGreen; } else { Shape1->Brush->Color = clRed; } } void __fastcall TForm2::FormCreate(TObject *Sender) { DateTimePicker1->Date = Now(); }
Have fun programming in 2016!


Did you know that this year we also have an additional Second?