Search code examples
mql4

How to find the number of days in the current month using MQL4?


Is there a built-in function or some elegant way to get the number of days in the current month using MQL4?

Or alternatively, is there a way to detect the last Monday of the current month?


Solution

  • A1: No, there is not a built-in function for this.

    A2: Yes, there are several elegant ways to solve this. One could be like this:

     int HowManyDaysInMONTH = { EMPTY,//    stump
                                31,   // Jan
                                28,   // Feb + int LeapYear( const int aDate ){...}
                                31,   // Mar
                                30,   // Aug
                                31,   // May
                                30,   // Jun
                                31,   // Jul
                                31,   // Aug
                                30,   // Sep
                                31,   // Oct
                                30,   // Nov
                                31    // Dec
                                };
    //-------------------------------------------------------------+
     int LeapYear( const int aDateToTEST ){
         return ( 366 == TimeDayOfYear( StringToTime( StringFormat( "%4d.12.31", TimeYear( aDateToTEST ) ) ) ) ? 1
                                                                                                               : 0
                  )
     }
    //-------------------------------------------------------------+
     PrintFormat( "This month has %d days",
                   HowManyDaysInMONTH[TimeMonth( aDateTODAY )]
                   );
    

    A3: Alternatively, one may implement such combination either.

    bool IsLastMondayOfMONTH( const int aDateTODAY ){
         return ( TimeDayOfWeek( aDateTODAY ) != 1 ? False
                                                   : TimeMonth( aDateTODAY ) == TimeMONTH ( aDateTODAY + 7 ) ? False
                                                                                                             : True
                  );
    }