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.
Arithmetic uses seconds: dt + 86400 advances the represented value by 24 hours. Calendar sessions, broker offset changes and daylight-saving transitions require separate rules.
Understanding the MQL5 datetime Type and Formatting
MQL5 datetime stores seconds from 1970, but the type carries no timezone identifier. A value obtained from broker-server time is not automatically a UTC timestamp. Keep the time source and any conversion explicit.
To display dates on charts or format log messages, call TimeToString with bitwise flags.
| Format Flag | Output Example | Typical 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
TimeToStruct extracts calendar fields without converting the timezone. A London or New York session rule needs an explicit mapping to broker time and daylight-saving rules; reading hour alone does not provide it.
- 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
This is an OnStart script saved under MQL5/Scripts, not a continuously running EA. It prints three time sources and evaluates one illustrative weekday window in server time. The helper supports start-inclusive/end-exclusive hours, including windows crossing midnight; equal hours are defined as closed. The current calendar weekday is used even for an overnight window.
Error handling & safety rules
No orders or Friday exits are implemented. A fixed Friday hour is not a universal market close or swap cutoff. TimeCurrent in this script is the last quote time for any selected Market Watch symbol and can be stale when quotes stop. Weekend exclusion is a sample policy, not the trading schedule of every instrument.
MQL5 Code Implementation
//+------------------------------------------------------------------+
//| 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)
{
if(startHour<0 || startHour>23 || endHour<0 || endHour>23 || startHour==endHour) return false;
MqlDateTime dt;
if(!TimeToStruct(serverTime, dt)) return false;
// Skip weekends (0 = Sunday, 6 = Saturday)
if(dt.day_of_week == 0 || dt.day_of_week == 6)
return false;
// Check hour window
if(startHour<endHour) return dt.hour>=startHour && dt.hour<endHour;
return dt.hour>=startHour || dt.hour<endHour;
}
//+------------------------------------------------------------------+
//| 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;
if(!TimeToStruct(serverNow, dt)) { Print("Cannot unpack server time"); return; }
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 (Hour Policy Matches)" : "NO (Hour Policy Does Not Match)");
}
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 generates editable MQL5 source code. Review its logic, request a syntax check, and compile and test the final file in MetaEditor.
Frequently Asked Questions
Related MQL5 pages
Technical references
Risk and testing note
These educational examples require independent compilation and testing. A compile pass or an illustrative setting does not establish execution correctness or profitability. Any reported performance must be supported by reproducible data and test settings; past results do not predict future returns. Trading involves significant risk of loss. This content is not financial advice.