Datetime & Duration in MATLAB

MATLAB Tutorial

Datetime & Duration in MATLAB

datetime and duration are MATLAB data types used to work with dates, times, and time intervals accurately—essential for time-series analysis, logs, experiments, and scheduling.
MATLAB is developed by MathWorks.


🔹 What’s the Difference?

TypePurposeExample
datetimeA specific point in time2026-01-17 13:45:00
durationLength of time02:30:00 (2 hours 30 min)

1️⃣ Create datetime Values

🔸 Current Date & Time


Output (example)

17-Jan-2026 13:45:12

 From Date String



 From Components (Y,M,D,H,M,S)



 Specify Display Format



2️⃣ Create duration Values

 From Hours, Minutes, Seconds



 Combine Durations


Output

02:30:45

 From Time String



3️⃣ Arithmetic with Datetime & Duration

 Add/Subtract Duration



 Difference Between Two Datetimes


Output

9 days

4️⃣ Extract Date & Time Components


 


5️⃣ Calendar Durations (Months/Years)

Use calendar units when months/years matter.


📌 Handles month length correctly (Feb).


6️⃣ Shift, Round & Compare Dates

 Shift to Start of Month


 Round to Nearest Hour


 Compare



7️⃣ Datetime Arrays & Time Zones



8️⃣ Timetables (Datetime as Time Axis)


📌 Perfect for time-series data.


⚠️ Important Notes

  • Prefer datetime over older datenum

  • Use duration for elapsed time, caldays/calmonths for calendar logic

  • timetable uses datetime as row times

  • Set Format for readable displays


🎯 Interview Questions: Datetime & Duration

🔹 Q1. Difference between datetime and duration?

Answer: datetime is a point in time; duration is a length of time.


🔹 Q2. How do you get the current time?

Answer: datetime('now').


🔹 Q3. How do you add 2 hours to a datetime?

Answer: dt + hours(2).


🔹 Q4. How do you find the difference between two dates?

Answer: Subtract them → returns a duration.


🔹 Q5. What are calendar durations?

Answer: Units like caldays, calmonths that respect calendar rules.


🔹 Q6. Which data type is best for time-series data?

Answer: timetable.


Summary

  • datetime = specific date & time

  • duration = time interval

  • Support arithmetic, formatting, time zones

  • Essential for logs, analytics, and time-series work

You may also like...