Complete MQL5 guide & code

MQL5 Datetime Guide: TimeToString, TimeToStruct & Session Filter Code

Complete reference for MQL5 datetime manipulation. Learn TimeToString flags, MqlDateTime struct unpacking, extracting hours and minutes, date arithmetic, and building an EA trading session filter.

What this MQL5 guide covers

The MQL5 datetime type is an 8-byte integer representing seconds elapsed since January 1, 1970 (Unix epoch).

TimeToString(dt, mode) formats timestamps into readable strings using TIME_DATE, TIME_MINUTES, and TIME_SECONDS flags.

TimeToStruct(dt, struct) unpacks a timestamp into individual year, month, day, hour, min, sec, and day_of_week fields.

Datetime arithmetic operates directly in seconds: adding one day is dt + 86400; subtracting two datetimes yields elapsed seconds.

Understanding the MQL5 datetime Type and Formatting

In MQL5, datetime variables store Unix timestamps. Because the underlying value is simply an integer count of seconds, date comparisons and arithmetic are computationally fast.

To display dates on charts or format log messages, call TimeToString with bitwise flags.

Format FlagOutput ExampleTypical Use Case
TIME_DATE"2026.09.14"Date-only reporting, daily journal keys
TIME_MINUTES"14:30"Intraday chart comments, session clocks
TIME_SECONDS"14:30:15"Execution logs, tick timestamp precision
TIME_DATE | TIME_MINUTES"2026.09.14 14:30"Standard order entry and position history timestamps
TIME_DATE | TIME_SECONDS"2026.09.14 14:30:15"High-frequency logging and backtest diagnostics

Extracting Hours, Minutes, and Days: MqlDateTime Struct

To filter trading activity by time of day (e.g. only trading during the London or New York session), convert datetime to an MqlDateTime structure using TimeToStruct.

  • dt_struct.hour: Current hour (0 to 23).
  • dt_struct.min: Current minute (0 to 59).
  • dt_struct.sec: Current second (0 to 59).
  • dt_struct.day_of_week: Day of week (0 = Sunday, 1 = Monday ... 5 = Friday, 6 = Saturday).
  • dt_struct.day: Day of month (1 to 31).

Datetime Arithmetic: Adding Days and Subtraction

Because datetime is denominated in seconds, arithmetic is straightforward:

Adding 1 day: datetime tomorrow = now + 86400 (or 24 * 3600).

Adding 1 week: datetime nextWeek = now + (7 * 86400).

Calculating elapsed time: (TimeCurrent() - orderOpenTime) yields elapsed seconds. Divide by 60 for minutes or 3600 for elapsed hours.

Implementation details & mechanics

Core implementation pattern

In OnTick(), call TimeCurrent() to obtain trade server time. Unpack with TimeToStruct(TimeCurrent(), dtStruct). Verify if dtStruct.hour >= InpStartHour && dtStruct.hour < InpEndHour. If the current server time is outside the permitted session, skip entry evaluation.

Error handling & safety rules

For time-based exits (e.g. intraday EAs closing all positions before Friday market close): check if dtStruct.day_of_week == 5 (Friday) and dtStruct.hour >= 21. If so, loop through open positions and close them via CTrade::PositionClose() to avoid weekend swap and gap risk.

MQL5 Code Implementation Code

//+------------------------------------------------------------------+
//|                                                DatetimeGuide.mq5 |
//|                             Copyright 2026, Pineify Guides Series |
//|                                              https://pineify.app |
//+------------------------------------------------------------------+
#property copyright "Pineify Guides Series"
#property link      "https://pineify.app/mql5/datetime-guide"
#property version   "1.00"
#property script_show_inputs

//--- Input parameters
input int InpSessionStartHour = 9;   // Session Start Hour (0-23)
input int InpSessionEndHour   = 17;  // Session End Hour (0-23)

//+------------------------------------------------------------------+
//| Helper: Check if current server time is in trading session       |
//+------------------------------------------------------------------+
bool IsInTradingSession(datetime serverTime, int startHour, int endHour)
  {
   MqlDateTime dt;
   TimeToStruct(serverTime, dt);

   // Skip weekends (0 = Sunday, 6 = Saturday)
   if(dt.day_of_week == 0 || dt.day_of_week == 6)
      return false;

   // Check hour window
   if(dt.hour >= startHour && dt.hour < endHour)
      return true;

   return false;
  }

//+------------------------------------------------------------------+
//| Script program start function                                    |
//+------------------------------------------------------------------+
void OnStart()
  {
   // 1. Current Datetime Functions
   datetime serverNow = TimeCurrent();       // Latest quote time on server
   datetime localNow  = TimeLocal();         // Local computer time
   datetime gmtNow    = TimeGMT();           // GMT / UTC time

   Print("--- Current Timestamps ---");
   Print("TimeCurrent(): ", TimeToString(serverNow, TIME_DATE|TIME_SECONDS));
   Print("TimeLocal():   ", TimeToString(localNow, TIME_DATE|TIME_SECONDS));
   Print("TimeGMT():     ", TimeToString(gmtNow, TIME_DATE|TIME_SECONDS));

   // 2. Extract Hour, Minute, Day with TimeToStruct
   MqlDateTime dt;
   TimeToStruct(serverNow, dt);
   PrintFormat("Unpacked Date -> Year: %d, Month: %02d, Day: %02d | Hour: %02d:%02d:%02d (Day of week: %d)",
               dt.year, dt.mon, dt.day, dt.hour, dt.min, dt.sec, dt.day_of_week);

   // 3. Datetime Arithmetic
   datetime tomorrow    = serverNow + 86400;           // Add 1 day
   datetime nextHour    = serverNow + 3600;            // Add 1 hour
   datetime weekAgo     = serverNow - (7 * 86400);     // Subtract 7 days

   Print("--- Date Arithmetic ---");
   Print("Plus 1 Day:  ", TimeToString(tomorrow, TIME_DATE|TIME_MINUTES));
   Print("Plus 1 Hour: ", TimeToString(nextHour, TIME_DATE|TIME_MINUTES));
   Print("Minus 7 Days:", TimeToString(weekAgo, TIME_DATE|TIME_MINUTES));

   // Calculate elapsed time between two timestamps
   long elapsedSeconds = (long)(tomorrow - serverNow);
   PrintFormat("Elapsed difference: %I64d seconds (%I64d hours)",
               elapsedSeconds, elapsedSeconds / 3600);

   // 4. Session Filter Test
   bool sessionActive = IsInTradingSession(serverNow, InpSessionStartHour, InpSessionEndHour);
   PrintFormat("Session active [%d:00 - %d:00]? %s",
               InpSessionStartHour, InpSessionEndHour,
               sessionActive ? "YES (Trading Permitted)" : "NO (Blocked)");
  }

Copy this code into MetaEditor, save it in your MQL5 folder (Experts, Scripts, or Include), and compile with F7.

Generate custom MQL5 code with Pineify AI

Describe the trade execution, indicator calculations, risk management, or data processing logic you need. Pineify produces clean, typed MQL5 source code ready to compile in MetaEditor.

Frequently Asked Questions

Related MQL5 pages

Technical references

Risk and testing note

Past performance is not indicative of future results. Backtest statistics are based on historical data and do not guarantee future profits. Trading involves significant risk of loss. This content is for educational purposes only and does not constitute financial advice.