Table of Contents
Calendar Arithmetic with `datetime`
When you work with datetime values, you often need to answer questions such as how many days lie between two dates, what date occurs three months from now, or how many business days pass in a given interval. MATLAB provides operators and functions that let you perform these kinds of calendar calculations directly on datetime and related types.
In this chapter you will focus on what is special about calculating with dates and times, not on how to create or format them, and not on plotting, which are treated separately.
Differences Between Dates and Times
The basic operation in date calculations is to subtract two date or time values. When you subtract two datetime values, MATLAB returns a duration that represents the elapsed time between them. For example, if t2 is later than t1, then t2 - t1 is a positive duration.
The same idea applies when subtracting datetime and duration, or two duration values. The numeric units embedded in the result depend on the type. A duration has time units such as hours, minutes, or seconds. A calendarDuration has calendar units such as years, months, and days. The difference between two datetime values is always a duration, not a calendarDuration, because it represents exact elapsed time, not a count of calendar months or years.
When you display a duration, MATLAB prints it in a fixed format, such as 5:00:00 for 5 hours or 3 days for three days. You can convert between units using appropriate functions if needed.
Subtracting and Comparing Datetimes
Date subtraction is written using the usual minus operator. If you have two datetime values, such as tStart and tEnd, then writing dt = tEnd - tStart produces a duration object that represents the elapsed time.
Once you have a duration, you can inspect its length in different units. MATLAB offers functions that extract the total number of days, hours, or seconds as a numeric value. This lets you express the same time difference in whatever units make sense for your problem, for example total days for long intervals or total seconds for short measurements.
Comparisons such as t1 < t2 or t1 == t2 work naturally for datetime values. The result is a logical value or array that tells you which dates occur earlier or later. This is particularly useful for filtering time based data, for example selecting all records that fall within a given date range.
You can also compare duration values in the same way, for example to test whether an elapsed time is longer than one hour. Comparisons between datetimes and durations are not valid, so you typically compare either datetime with datetime or duration with duration.
Durations in Days, Hours, and Seconds
The result of subtracting two datetimes is a duration. This type can represent partial days and fractions of a second accurately. When you display a duration, MATLAB uses a default format that shows hours, minutes, and seconds or includes days if needed.
To work with a duration numerically, you often convert it to a scalar count in one particular unit. MATLAB provides functions that return a double precision value equal to the total number of days, hours, minutes, or seconds represented by the duration. For example, a two and a half day interval would return 2.5 if converted to days and 60 when converted to hours.
Because duration is its own type, you can also add or subtract it from datetimes, or add and subtract it from other durations. Multiplying a duration by a numeric scalar scales it so you can easily double or halve a time interval. Division of a duration by a scalar or by another duration is also valid. Dividing one duration by another returns a unitless numeric ratio that tells you how many times one interval fits into another.
A duration always represents exact elapsed time. It does not know anything about months or years. That is the key difference between duration and calendarDuration.
Calendar Durations: Years, Months, Days
Sometimes you want to express a time offset in calendar units such as "3 months" or "1 year and 6 months". These units do not have a fixed length in hours or days, because months and years vary in length. For this purpose MATLAB provides the calendarDuration type.
A calendarDuration can contain components for years, months, and days, as well as time of day. You typically create one with a constructor that accepts numeric counts for years, months, and days. For example, a calendar interval that represents two years and three months can be built by passing those counts in. You can also include a time component.
The distinction between duration and calendarDuration matters whenever months and years are involved. A calendar duration of one month added to some dates yields different elapsed times in days, depending on the starting month. This behavior matches calendar arithmetic in everyday life. A fixed duration of 30 days, in contrast, always represents exactly 30 days, which may or may not equal one calendar month.
Because of this, you use calendarDuration when you care about calendar structure such as months and years, and duration when you care about physical elapsed time such as total hours or seconds.
Adding and Subtracting Time Offsets
Once you have a duration or calendarDuration, you can add it to or subtract it from a datetime value using the same arithmetic operators you use for numbers. Adding a positive duration moves a date forward in time, and subtracting it moves a date backward. The same is true for calendar durations.
For example, if you have a datetime marking the start of an experiment, you can produce the time one hour later by adding a duration of one hour. If you have monthly billing dates, you can move from one billing date to the next by adding a calendar duration of one month.
Adding durations to durations is also meaningful. It produces a new duration equal to the sum of the intervals. The same is true for calendar durations. You cannot, however, create a meaningful sum that mixes duration and calendarDuration directly. Instead, you should decide whether your calculation belongs in elapsed time or in calendar time and stay within that type.
In vectorized computations, you can add a single duration or calendarDuration to an entire array of datetimes at once. This is a common pattern when shifting schedules, generating timelines, or constructing forecasts.
Counting Whole Days, Weeks, Months, and Years
A common task is to count how many whole calendar units lie between two dates. For example, you might need the number of whole days, or the number of complete months, between a start and end date.
To count whole days or other fixed units, you can use a duration and then extract the total days or hours as a numeric value. This returns a real number that can include fractions. If you care only about whole days or weeks, you then apply rounding functions to that value. For example, the floor of the total number of days counts whole days that have fully elapsed.
Months and years require a calendar interpretation. A duration alone cannot tell you how many calendar months lie between two dates because months differ in length. Instead, MATLAB provides functions that count whole calendar units between two datetime values when you specify the unit. The result is an integer or array of integers that represent how many complete units in that sense fit between the dates. You can request years, quarters, months, weeks, days, or other supported units.
In this way you can calculate, for instance, how many full months of a subscription have been completed, how many whole weeks of data lie between two timestamps, or how many calendar years have passed since a baseline date.
Rounding Dates and Times
Rounding is important whenever you want to align dates and times to regular boundaries such as the start of a day, the nearest hour, or the end of a month. MATLAB provides functions that round datetime values to the nearest, previous, or next boundary of a specified time unit.
When you round to units like seconds, minutes, or hours, MATLAB adjusts the time of day while leaving the date itself unchanged unless the rounding crosses midnight. For example, rounding a time that is 10:29 to the nearest hour yields 10:00, while 10:31 rounds to 11:00. Rounding to days or larger units can shift the date as well.
The same style of functions exists for durations. You can round a duration to the nearest second, minute, or other supported unit. This is often useful when your data contains small numerical noise in timestamps and you want to clean them to regular spacing.
You should choose rounding direction according to your application. Rounding toward zero, toward negative infinity, or toward positive infinity can all be meaningful in different contexts, for example when measuring service level agreements or counting whole periods.
Working with Business Days and Custom Calendars
Real world date calculations often care about working days rather than simple calendar days. MATLAB includes tools that work with financial calendars, including functions that treat weekends and possibly holidays as nonbusiness days. With these, you can count business days between two dates, move a date forward a specified number of business days, or identify whether a date is a business day or not.
These functions generally work with datetime values and a specified business day convention. You can specify which weekdays count as weekends, for example Saturday and Sunday, or Friday and Saturday in some regions. For more sophisticated calendars you can also specify holiday lists and let the functions skip those days as well.
When you move a date forward by a number of business days, the function skips weekends and holidays according to the rules you supply and returns the resulting datetime. Counting business days between two dates returns a numeric value that you can use in scheduling, financial accruals, or resource planning.
Although these tools belong mainly to specialized toolboxes, the concepts apply generally when you work with time in a business context. You often need to distinguish simple day counts from business day counts, and you should be clear which one your calculation uses.
Working Across Time Zones and Daylight Saving Changes
Date calculations can become subtle when time zones or daylight saving transitions are involved. A datetime in MATLAB can carry a time zone. When it does, operations like subtraction and addition interpret the times in that zone and account for shifts due to daylight saving rules.
Subtracting two zoned datetimes that represent local times in the same zone still yields a duration that reflects true elapsed time. For example, if a daylight saving shift causes the clock to jump forward or backward, the resulting duration includes or excludes that missing or repeated hour. When you add a duration to a zoned datetime, MATLAB adjusts the underlying absolute time and then recalculates the local wall clock time, which may show a different shift around the transition.
Because of this, you should be careful when interpreting differences between local times that span these transitions. A difference of one calendar day in local wall time might not be exactly 24 hours if a daylight saving change lies between the two timestamps.
If you do not need time zone behavior, you can leave the time zone of your datetimes unset, in which case MATLAB treats them as naive times. If you do care about absolute time across locations, you should set a proper time zone and be aware that daylight saving rules will affect apparent durations.
Important points to remember:
Date subtraction between two datetime values returns a duration that represents exact elapsed time.
Use duration for fixed units like hours or seconds, and calendarDuration when you care about calendar units like months or years.
Counting whole months or years between dates requires calendar aware functions, not simple day counts.
Rounding dates to units like days or hours is essential when aligning time based data and should be done with explicit rounding functions.
Time zones and daylight saving changes affect date differences, so zoned datetimes require extra care in interpretation.