Datetime & Duration in MATLAB

⏰ 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?
| Type | Purpose | Example |
|---|---|---|
| datetime | A specific point in time | 2026-01-17 13:45:00 |
| duration | Length of time | 02:30:00 (2 hours 30 min) |
1️⃣ Create datetime Values
🔸 Current Date & Time
Output (example)
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
From Time String
3️⃣ Arithmetic with Datetime & Duration
Add/Subtract Duration
Difference Between Two Datetimes
Output
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
datetimeover olderdatenumUse duration for elapsed time, caldays/calmonths for calendar logic
timetableusesdatetimeas row timesSet
Formatfor 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 & timeduration= time intervalSupport arithmetic, formatting, time zones
Essential for logs, analytics, and time-series work
