17.3. Date Calculations and Differences
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.
Views: 0
Where to Move
Move chapter:
- ☰ 1. Getting Started with MATLAB
- ☰ 1.1. What Is MATLAB and What Is It Used For
- ☰ 1.2. Installing MATLAB and Setting Up the Environment
- ☰ 1.3. Understanding the MATLAB Desktop Interface
- ☰ 1.4. Command Window, Workspace, and Current Folder
- ☰ 1.5. Basic Workflow and Running Simple Commands
- ☰ 1.6. Getting Help and Documentation
-
- ☰ 2. MATLAB Language Basics
- ☰ 2.1. MATLAB Syntax and Expressions
- ☰ 2.2. Variables and Assignment
- ☰ 2.3. Data Types and Type Conversion
- ☰ 2.4. Vectors and Matrices Fundamentals
- ☰ 2.5. Creating and Indexing Arrays
- ☰ 2.6. Basic Arithmetic and Elementwise Operations
- ☰ 2.7. Using Built-In Constants and Functions
-
- ☰ 3. Working with Variables and the Workspace
- ☰ 3.1. Creating, Viewing, and Editing Variables
- ☰ 3.2. Workspace Browser and Variable Inspector
- ☰ 3.3. Saving and Loading Data Files
- ☰ 3.4. MAT-Files and Importing External Data
- ☰ 3.5. Clearing Variables and Managing the Workspace
-
- ☰ 4. Vectors, Matrices, and Arrays
- ☰ 4.1. Row and Column Vectors
- ☰ 4.2. Matrix Creation and Concatenation
- ☰ 4.3. Indexing, Slicing, and Logical Indexing
- ☰ 4.4. Matrix Operations vs Elementwise Operations
- ☰ 4.5. Reshaping and Rearranging Arrays
- ☰ 4.6. Special Matrices and Functions
-
- ☰ 5. Basic Programming Constructs
- ☰ 5.1. Scripts vs Functions
- ☰ 5.2. Control Flow with if, elseif, else
- ☰ 5.3. Loops with for and while
- ☰ 5.4. break, continue, and return
- ☰ 5.5. Logical Expressions and Relational Operators
- ☰ 5.6. Best Practices for Clear and Readable Code
-
- ☰ 6. Functions in MATLAB
- ☰ 6.1. Creating Simple Functions
- ☰ 6.2. Function Inputs and Outputs
- ☰ 6.3. Function Files and the Path
- ☰ 6.4. Local vs Global Variables
- ☰ 6.5. Anonymous Functions
- ☰ 6.6. Organizing Code into Multiple Functions
-
- ☰ 7. Working with Numbers and Math
- ☰ 7.1. Scalars and Vectorized Computations
- ☰ 7.2. Basic Mathematical Functions
- ☰ 7.3. Trigonometric and Exponential Functions
- ☰ 7.4. Complex Numbers in MATLAB
- ☰ 7.5. Rounding, Modulo, and Special Values
- ☰ 7.6. Numerical Precision and Floating Point Considerations
-
- ☰ 8. Strings, Characters, and Categorical Data
- ☰ 8.1. Character Arrays and String Arrays
- ☰ 8.2. Creating and Manipulating Strings
- ☰ 8.3. Converting Between Data Types and Strings
- ☰ 8.4. Comparing and Searching Strings
- ☰ 8.5. Categorical Arrays Basics
-
- ☰ 9. Tables, Structures, and Cell Arrays
- ☰ 9.1. Introduction to Tables
- ☰ 9.2. Creating Tables and Accessing Data
- ☰ 9.3. Modifying and Joining Tables
- ☰ 9.4. Structures and Nested Structures
- ☰ 9.5. Cell Arrays and Cell Indexing
- ☰ 9.6. Choosing the Right Container Type
-
- ☰ 10. Importing and Exporting Data
- ☰ 10.1. Reading Text and CSV Files
- ☰ 10.2. Importing Excel Spreadsheets
- ☰ 10.3. Importing Data with the Import Tool
- ☰ 10.4. Exporting Data to Files
- ☰ 10.5. Working with Image and Audio Files
- ☰ 10.6. Basic File Management from MATLAB
-
- ☰ 11. Plotting and Visualization
- ☰ 11.1. Introduction to 2D Plotting
- ☰ 11.2. Customizing Plots and Axes
- ☰ 11.3. Multiple Plots in One Figure
- ☰ 11.4. Labels, Titles, Legends, and Annotations
- ☰ 11.5. Plotting with Different Line and Marker Styles
- ☰ 11.6. Saving and Exporting Figures
-
- ☰ 12. Advanced Plotting for Beginners
- ☰ 12.1. Subplots and Tiled Layouts
- ☰ 12.2. Bar, Scatter, and Stem Plots
- ☰ 12.3. Histograms and Density Plots
- ☰ 12.4. 3D Plots and Surface Plots
- ☰ 12.5. Using plottools and Interactive Editing
- ☰ 12.6. Basics of Handle Graphics
-
- ☰ 13. Working with Scripts and Live Scripts
- ☰ 13.1. Creating and Running Script Files
- ☰ 13.2. Sectioning Code and Running Sections
- ☰ 13.3. Live Scripts and Rich Text
- ☰ 13.4. Adding Equations, Images, and Outputs
- ☰ 13.5. Sharing and Exporting Live Scripts
-
- ☰ 14. Debugging and Code Quality
- ☰ 14.1. Finding and Fixing Syntax Errors
- ☰ 14.2. Setting Breakpoints and Stepping Through Code
- ☰ 14.3. Inspecting Variable Values During Execution
- ☰ 14.4. Using the Editor Debugging Tools
- ☰ 14.5. Using Code Analyzer and Warnings
- ☰ 14.6. Writing Clean and Maintainable MATLAB Code
-
- ☰ 15. Basic Linear Algebra with MATLAB
- ☰ 15.1. Vectors and Norms
- ☰ 15.2. Matrix Addition and Multiplication
- ☰ 15.3. Solving Linear Systems with Backslash
- ☰ 15.4. Inverses, Determinants, and Rank
- ☰ 15.5. Eigenvalues and Eigenvectors
- ☰ 15.6. Using Linear Algebra Functions Safely
-
- ☰ 16. Data Analysis and Statistics Fundamentals
- ☰ 16.1. Descriptive Statistics and Summary Measures
- ☰ 16.2. Sorting, Filtering, and Grouping Data
- ☰ 16.3. Basic Correlation and Regression
- ☰ 16.4. Simple Data Cleaning Techniques
- ☰ 16.5. Basic Time Series Handling
-
- ☰ 17. Working with Time and Dates
- ☰ 17.1. Representing Dates and Times
- ☰ 17.2. Creating and Formatting datetime Arrays
- ☰ 17.3. Date Calculations and Differences
- ☰ 17.4. Plotting Data over Time
-
- ☰ 18. Introduction to Signal and Image Handling
- ☰ 18.1. Basic Signal Representation in MATLAB
- ☰ 18.2. Simple Filtering and Transformations
- ☰ 18.3. Reading, Displaying, and Writing Images
- ☰ 18.4. Basic Image Transformations
-
- ☰ 19. Automation and Scripting Tasks
- ☰ 19.1. Batch Processing of Files
- ☰ 19.2. Writing Reusable Utility Scripts
- ☰ 19.3. Using Relative Paths and the MATLAB Path
- ☰ 19.4. Simple User Interaction with input and disp
-
- ☰ 20. Introduction to Toolboxes
- ☰ 20.1. What Are Toolboxes and How to Use Them
- ☰ 20.2. Exploring Installed Toolboxes
- ☰ 20.3. Finding Functions in Toolboxes
- ☰ 20.4. Add-Ons and MATLAB File Exchange
-
- ☰ 21. Best Practices and Next Steps
- ☰ 21.1. Organizing Projects and Folders
- ☰ 21.2. Version Control Basics with MATLAB
- ☰ 21.3. Performance Tips for Beginners
- ☰ 21.4. Learning Resources and Documentation Path
- ☰ 21.5. Suggested Practice Projects for Beginners
-
Comments
Please login to add a comment.
Don't have an account? Register now!