Expert Advisors • Indicators • Scripts • Libraries

MQL.RobotFX.org is the biggest collection of MetaTrader expert advisors (MT5 & MT4), indicators, scripts and libraries that can be used to improve trading results, minimize risks or simply automate trading tasks

MetaTrader 5 Libraries | High-Performance Time Functions (TimeUtils)

MetaTrader Experts, Indicators, Scripts and Libraries

This library contains more than 80 different functions to deal with time variables. The primary aim is to provide high-performance time functions. The performance mode (which can be controlled at compile time via a #define) is disabled by default. This mode is not a requirement to include the library into your projects, as it can be included normally without it.

TIMEUTILS_PERFORMANCE_MODE

Optionally, performance-mode can be switched on at compile time via #defines before #include:

// enable performance mode for library #define TIMEUTILS_PERFORMANCE_MODE #include "TimeUtils.mqh"  

This will redirect all calls to MQL's built-in TimeToStruct and StructToTime functions to more efficient alternatives.

You can compile the script "performance_mode.mq5" with and without TIMEUTILS_PERFORMANCE_MODE to check for the difference in speed on your machine. This will be beneficial to high-performance programs performing heavy or many time-related tasks (e.g., scanning all the quotes history for H1 bars at the start of trading weeks or collecting other statistics).

Listing of all functions in the library:

The function names should be self-explanatory; also, you can find a short description for a specific function in the TimeUtils.mqh file.

//+==================================================================+ //| Create datetime From Components                                  | //+==================================================================+ datetime CreateDateTime(    const int year,           // Year    const int mon,            // Month    const int day,            // Day    const int hour = 0,       // Hour    const int min = 0,        // Minutes    const int sec = 0         // Seconds    ) datetime CreateDateTime(MqlDateTime&  dt_struct);  // fast alternative to StructToTime()  //+==================================================================+ //| Break datetime To Components                                     | //+==================================================================+ bool TimeToStructFast(    datetime      dt,         // Date value to convert    MqlDateTime&  dt_struct   // structure for the adoption of values    )  //+==================================================================+ //| Extract Components of datetime: Sunday, yyyy.mm.dd hh:mm:ss      | //| Get() Units                                                      | //+==================================================================+ int GetSecond(datetime t) int GetMinute(datetime t) int GetHour(datetime t) int GetDay(datetime t) int GetMonth(datetime t) int GetYear(datetime t)  //+==================================================================+ //| Day() Number                                                     | //+==================================================================+ int DayOfWeek(datetime t) int DayOfYear(datetime t) int DayIndex(datetime t)  //+==================================================================+ //| Week() Number                                                    | //+==================================================================+ int WeekOfMonth(const datetime t, bool StartsOnMonday = false) int WeekOfYear(const datetime t, bool StartsOnMonday = false) int WeekIndex(datetime t, bool StartsOnMonday = false)  //+==================================================================+ //| StartOf() Units                                                  | //+==================================================================+ datetime StartOfMinute(datetime t) datetime StartOfHour(datetime t) datetime StartOfDay(datetime t) datetime StartOfWeek(datetime t, bool StartsOnMonday = false) datetime StartOfMonth(datetime t) datetime StartOfYear(datetime t)  //+==================================================================+ //| EndOf() Units                                                    | //+==================================================================+ datetime EndOfMinute(datetime t) datetime EndOfHour(datetime t) datetime EndOfDay(datetime t) datetime EndOfWeek(datetime t, bool StartsOnMonday = false) datetime EndOfMonth(datetime t) datetime EndOfYear(datetime t)  //+==================================================================+ //| SecsElapsedOf() Units                                            | //+==================================================================+ int SecsElapsedOfMinute(datetime t) int SecsElapsedOfHour(datetime t) int SecsElapsedOfDay(datetime t) int SecsElapsedOfWeek(datetime t, bool StartsOnMonday = false) int SecsElapsedOfMonth(datetime t) int SecsElapsedOfYear(datetime t)  //+==================================================================+ //| RoundTo() / Nearest() Units                                      | //+==================================================================+ datetime RoundToMinute(datetime t) datetime RoundToHour(datetime t) datetime RoundToDay(datetime t) datetime RoundToWeek(datetime t, bool StartsOnMonday = false)  //+==================================================================+ //| CeilTo() / Next() Units                                          | //+==================================================================+ datetime CeilToMinute(datetime t) datetime CeilToHour(datetime t) datetime CeilToDay(datetime t) datetime CeilToWeek(datetime t, bool StartsOnMonday = false)  //+==================================================================+ //| Next() Weekday                                                   | //+==================================================================+ datetime NextWeekday(datetime t, ENUM_DAY_OF_WEEK weekday = SUNDAY) datetime NextSunday(datetime t) datetime NextMonday(datetime t) datetime NextTuesday(datetime t) datetime NextWednesday(datetime t) datetime NextThursday(datetime t) datetime NextFriday(datetime t) datetime NextSaturday(datetime t)  //+==================================================================+ //| Previous() Weekday                                               | //+==================================================================+ datetime PreviousWeekday(datetime t, ENUM_DAY_OF_WEEK weekday = SUNDAY) datetime PreviousSunday(datetime t) datetime PreviousMonday(datetime t) datetime PreviousTuesday(datetime t) datetime PreviousWednesday(datetime t) datetime PreviousThursday(datetime t) datetime PreviousFriday(datetime t) datetime PreviousSaturday(datetime t)  //+==================================================================+ //| Nth() Weekday Of The Month                                       | //+==================================================================+ datetime FirstWeekdayOfTheMonth(datetime t, ENUM_DAY_OF_WEEK weekday = SUNDAY) datetime LastWeekdayOfTheMonth(datetime t, ENUM_DAY_OF_WEEK weekday = SUNDAY) datetime NthWeekdayOfTheMonth(datetime t, int Nth, ENUM_DAY_OF_WEEK weekday = SUNDAY)  //+==================================================================+ //| Add() Units                                                      | //+==================================================================+ datetime AddSeconds(datetime t, int amount) datetime AddMinutes(datetime t, int amount) datetime AddHours(datetime t, int amount) datetime AddDays(datetime t, int amount) datetime AddBusinessDays(datetime t, int amount) datetime AddWeeks(datetime t, int amount) datetime AddMonths(datetime t, int amount) datetime AddYears(datetime t, int amount)  //+==================================================================+ //| Sub() Units                                                      | //+==================================================================+ datetime SubSeconds(datetime t, int amount) datetime SubMinutes(datetime t, int amount) datetime SubHours(datetime t, int amount) datetime SubDays(datetime t, int amount) datetime SubBusinessDays(datetime t, int amount) datetime SubWeeks(datetime t, int amount) datetime SubMonths(datetime t, int amount) datetime SubYears(datetime t, int amount)  //+==================================================================+ //| DifferenceIn() Units                                             | //+==================================================================+ int DifferenceInCalendarDays(datetime beginTime, datetime endTime) int DifferenceInBusinessDays(datetime beginTime, datetime endTime) int DifferenceInCalendarWeeks(datetime beginTime, datetime endTime, bool StartsOnMonday = false) int DifferenceInCalendarMonths(datetime beginTime, datetime endTime)  //+==================================================================+ //| IsSame() Units                                                   | //+==================================================================+ bool IsSameMinute(datetime t1, datetime t2) bool IsSameHour(datetime t1, datetime t2) bool IsSameDay(datetime t1, datetime t2) bool IsSameWeek(datetime t1, datetime t2, bool StartsOnMonday = false) bool IsSameMonth(datetime t1, datetime t2) bool IsSameYear(datetime t1, datetime t2)  //+==================================================================+ //| IsCurrent() Units                                                | //+==================================================================+ bool IsCurrentMinute(datetime t) bool IsCurrentHour(datetime t) bool IsCurrentWeek(datetime t, bool StartsOnMonday = false) bool IsCurrentMonth(datetime t) bool IsCurrentYear(datetime t) bool IsToday(datetime t) bool IsTomorrow(datetime t) bool IsYesterday(datetime t)  //+==================================================================+ //| Misc                                                             | //+==================================================================+ bool IsLeapYear(int year) int  DaysInMonth(int year, int month) datetime GetNthWeekdayInYearMonth(iYear, iMonth, Nth, weekday = SUNDAY) datetime GetNthSundayInYearMonth(iYear, iMonth, Nth)  //+==================================================================+ //| Formating Time to String                                         | //+==================================================================+ string t2s(datetime t, const int mode = TIME_DATE | TIME_MINUTES) string SecondsToString(int seconds) string TimeFormat(datetime t, string format = "YYYY.MM.DD hh:mm")  

List of all available time formats:

//+------------------------------------------------------------------+ //| Get the formatted time according to the passed string of tokens. | //| List of all available formats:                                   | //| Format  Output            Description                            | //| ------  ----------------  -------------------------------------  | //| YY      18                Two-digit year                         | //| YYYY    2018              Four-digit year                        | //| M       1-12              The month, beginning at 1              | //| MM      01-12             The month, 2-digits                    | //| MMM     Jan-Dec           The abbreviated month name, 3-letters  | //| MMMM    January-December  The full month name                    | //| D       1-31              The day of the month                   | //| DD      01-31             The day of the month, 2-digits         | //| DDD     Sun-Sat           The short name of the day of the week  | //| DDDD    Sunday-Saturday   The name of the day of the week        | //| h       0-23              The hour                               | //| hh      00-23             The hour, 2-digits                     | //| H       1-12              The hour, 12-hour clock                | //| HH      01-12             The hour, 12-hour clock, 2-digits      | //| m       0-59              The minute                             | //| mm      00-59             The minute, 2-digits                   | //| s       0-59              The second                             | //| ss      00-59             The second, 2-digits                   | //| A       AM PM                                                    | //| a       am pm                                                    | //+------------------------------------------------------------------+ //| Sample formats:                                                  | //| "YYYY.MM.DD hh:mm"           // "2024.12.08 22:05"  (default)    | //| "DDD, YYYY.MM.DD hh:mm:ss"   // "Sun, 2024.12.08 22:05:21"       | //| "D MMMM YYYY, HH:mm a"       // "8 December 2024, 10:05 pm"      | //| "DD/MM/YYYY"                 // "08/12/2024"                     | //+------------------------------------------------------------------+ string TimeFormat(const datetime t, const string format = "YYYY.MM.DD hh:mm");  

The two attached scripts "basic.mq5" and "advanced.mq5" shows the basic and advanced usage examples.

An example output from "advanced.mq5" script:

/*  example output:   1. CreateDateTime(2022, 03, 25) = 2022.03.25 00:00:00      [year] [mon] [day] [hour] [min] [sec] [day_of_week] [day_of_year]  [0]   2024    12    18     17    27    25             3           352  2. t2s(t, TIME_DATE|TIME_SECONDS) = Wed, 2024.12.18 18:27:25  3. GetYear(t) = 2024  4. GetMonth(t) = 12  5. GetDay(t) = 18  6. GetHour(t) = 18  7. GetMinute(t) = 27  8. GetSecond(t) = 25  9. DayOfWeek(t) = 3  10. DayOfYear(t) = 352  11. DayIndex(t) = 20075  12. WeekOfMonth(t) = 3  13. WeekOfYear(t) = 51  14. WeekIndex(t) = 2868  15. WeekOfMonth(t, true) = 4  16. WeekOfYear(t, true) = 51  17. WeekIndex(t, true) = 2868  18. StartOfMinute(t) = 2024.12.18 18:27:00  19. StartOfHour(t) = 2024.12.18 18:00:00  20. StartOfDay(t) = 2024.12.18 00:00:00  21. StartOfWeek(t) = 2024.12.15 00:00:00  22. StartOfWeek(t, true) = 2024.12.16 00:00:00  23. StartOfMonth(t) = 2024.12.01 00:00:00  24. StartOfYear(t) = 2024.01.01 00:00:00  25. EndOfMinute(t) = 2024.12.18 18:27:59  26. EndOfHour(t) = 2024.12.18 18:59:59  27. EndOfDay(t) = 2024.12.18 23:59:59  28. EndOfWeek(t) = 2024.12.21 23:59:59  29. EndOfWeek(t, true) = 2024.12.22 23:59:59  30. EndOfMonth(t) = 2024.12.31 23:59:59  31. EndOfYear(t) = 2024.12.31 23:59:59  32. SecsElapsedOfMinute(t) = 25  33. SecsElapsedOfHour(t) = 1645  34. SecsElapsedOfDay(t) = 66445  35. SecsElapsedOfWeek(t) = 325645  36. SecsElapsedOfWeek(t, true) = 239245  37. SecsElapsedOfMonth(t) = 1535245  38. SecsElapsedOfYear(t) = 30479245  39. RoundToMinute(t) = 2024.12.18 18:27:00  40. RoundToHour(t) = 2024.12.18 18:00:00  41. RoundToDay(t) = 2024.12.19 00:00:00  42. RoundToWeek(t) = 2024.12.22 00:00:00  43. RoundToWeek(t, true) = 2024.12.16 00:00:00  44. CeilToMinute(t) = 2024.12.18 18:28:00  45. CeilToHour(t) = 2024.12.18 19:00:00  46. CeilToDay(t) = 2024.12.19 00:00:00  47. CeilToWeek(t) = 2024.12.22 00:00:00  48. CeilToWeek(t, true) = 2024.12.23 00:00:00  49. NextSunday(t) = 2024.12.22 00:00:00  50. NextMonday(t) = 2024.12.23 00:00:00  51. NextTuesday(t) = 2024.12.24 00:00:00  52. NextWednesday(t) = 2024.12.25 00:00:00  53. NextThursday(t) = 2024.12.19 00:00:00  54. NextFriday(t) = 2024.12.20 00:00:00  55. NextSaturday(t) = 2024.12.21 00:00:00  56. PreviousSunday(t) = 2024.12.15 00:00:00  57. PreviousMonday(t) = 2024.12.16 00:00:00  58. PreviousTuesday(t) = 2024.12.17 00:00:00  59. PreviousWednesday(t) = 2024.12.11 00:00:00  60. PreviousThursday(t) = 2024.12.12 00:00:00  61. PreviousFriday(t) = 2024.12.13 00:00:00  62. PreviousSaturday(t) = 2024.12.14 00:00:00  63. FirstWeekdayOfTheMonth(t, SUNDAY) = 2024.12.01 00:00:00  64. LastWeekdayOfTheMonth(t, SUNDAY) = 2024.12.29 00:00:00  65. AddSeconds(t, 30) = 2024.12.18 18:27:55  66. AddMinutes(t, 30) = 2024.12.18 18:57:25  67. AddHours(t, 2) = 2024.12.18 20:27:25  68. AddDays(t, 10) = 2024.12.28 18:27:25  69. AddBusinessDays(t, 10) = 2025.01.01 18:27:25  70. AddWeeks(t, 4) = 2025.01.15 18:27:25  71. AddMonths(t, 2) = 2025.02.18 18:27:25  72. AddYears(t, 5) = 2029.12.18 18:27:25  73. SubSeconds(t, 30) = 2024.12.18 18:26:55  74. SubMinutes(t, 30) = 2024.12.18 17:57:25  75. SubHours(t, 2) = 2024.12.18 16:27:25  76. SubDays(t, 10) = 2024.12.08 18:27:25  77. SubBusinessDays(t, 10) = 2024.12.04 18:27:25  78. SubWeeks(t, 4) = 2024.11.20 18:27:25  79. SubMonths(t, 2) = 2024.10.18 18:27:25  80. SubYears(t, 5) = 2019.12.18 18:27:25  81. DifferenceInCalendarDays(t, AddWeeks(t, 9)) = 63  82. DifferenceInBusinessDays(t, AddWeeks(t, 9)) = 45  83. DifferenceInCalendarWeeks(t, AddWeeks(t, 9)) = 9  84. DifferenceInCalendarWeeks(t, AddWeeks(t, 9), true) = 9  85. DifferenceInCalendarMonths(t, AddWeeks(t, 9)) = 2  86. IsSameMinute(t, AddHours(t, 25)) = false  87. IsSameHour(t, AddHours(t, 25)) = false  88. IsSameDay(t, AddHours(t, 25)) = false  89. IsSameWeek(t, AddHours(t, 25)) = true  90. IsSameWeek(t, AddHours(t, 25), true) = true  91. IsSameMonth(t, AddHours(t, 25)) = true  92. IsSameYear(t, AddHours(t, 25)) = true  93. IsCurrentMinute(t) = false  94. IsCurrentHour(t) = false  95. IsCurrentWeek(t) = true  96. IsCurrentWeek(t, true) = true  97. IsCurrentMonth(t) = true  98. IsCurrentYear(t) = true  99. IsToday(t) = true  100. IsTomorrow(t) = false  101. IsYesterday(t) = false  102. IsLeapYear(2100) = false  103. DaysInMonth(2024, 2) = 29  104. GetNthWeekdayInYearMonth(2024, 1, 1, SUNDAY) = 2024.01.07 00:00:00  105. t2s(TimeCurrent()) = Wed, 2024.12.18 17:27  106. SecondsToString(SecsElapsedOfDay(TimeCurrent())) = 17:27:25  107. TimeFormat(TimeCurrent(), YYYY.MM.DD hh:mm) = 2024.12.18 17:27  108. TimeFormat(TimeCurrent(), DDD, YYYY.MM.DD hh:mm:ss) = Wed, 2024.12.18 17:27:25  109. TimeFormat(TimeCurrent(), D MMM YYYY, HH:mm a) = 18 Dec 2024, 05:27 pm  */ 

Updates:

2024.12.03 - v.1.10 : Initial release.

2024.12.05 - v.1.15 : Added functions for business days and for Nth() weekday of the month. Optimized calculations in DaysInMonth() function.

2024.12.09 - v.1.20 : Added TimeFormat() function to format the time according to the passed string of tokens.

2024.12.09 - v.1.25 : Optimized calculations in TimeToStructFast() function.

2024.12.10 - v.1.30 : Optimized TimeFormat(), StartOfYear() and EndOfYear() functions. Updated descriptions of some functions.

2024.12.15 - v.1.35 : Optimized GetNthWeekdayInYearMonth() function.

2024.12.18 - v.1.40 : Added IsCurrentXXX(), IsToday(), IsTomorrow() and IsYesterday() functions.

2024.12.19 - v.1.45 : Optimized AddMonths() and GetNthWeekdayInYearMonth() functions.

2024.12.20 - v.1.50 : More code clean-up.

2024.12.21 - v.1.55 : Simplified calculations in AddMonths(): replaced the complex logic of adjusting months and years with a simpler total months calculation.

53970