Represent Dates and Times in MATLAB - MATLAB & Simulink (original) (raw)

The primary way to store date and time information is in datetime arrays, which support arithmetic, sorting, comparisons, plotting, and formatted display. The results of arithmetic differences are returned in duration arrays or, when you use calendar-based functions, in calendarDuration arrays.

For example, create a MATLABĀ® datetime array that represents two dates: June 28, 2014 at 6 a.m. and June 28, 2014 at 7 a.m. Specify numeric values for the year, month, day, hour, minute, and second components for the datetime.

t = datetime(2014,6,28,6:7,0,0)

t = 28-Jun-2014 06:00:00 28-Jun-2014 07:00:00

Change the value of a date or time component by assigning new values to the properties of the datetime array. For example, change the day number of each datetime by assigning new values to the Day property.

t =

27-Jun-2014 06:00:00 28-Jun-2014 07:00:00

Change the display format of the array by changing its Format property. The following format does not display any time components. However, the values in the datetime array do not change.

t.Format = 'MMM dd, yyyy'

t = Jun 27, 2014 Jun 28, 2014

If you subtract one datetime array from another, the result is a duration array in units of fixed length.

t2 = datetime(2014,6,29,6,30,45)

t2 =

29-Jun-2014 06:30:45

By default, a duration array displays in the format, hours:minutes:seconds. Change the display format of the duration by changing its Format property. You can display the duration value with a single unit, such as hours.

d =

48.512 hrs 23.512 hrs

You can create a duration in a single unit using the seconds, minutes, hours, days, or years functions. For example, create a duration of 2 days, where each day is exactly 24 hours.

You can create a calendar duration in a single unit of variable length. For example, one month can be 28, 29, 30, or 31 days long. Specify a calendar duration of 2 months.

Use the caldays, calweeks, calquarters, and calyears functions to specify calendar durations in other units.

Add a number of calendar months and calendar days. The number of days remains separate from the number of months because the number of days in a month is not fixed, and cannot be determined until you add the calendar duration to a specific datetime.

L = calmonths(2) + caldays(35)

Add calendar durations to a datetime to compute a new date.

t2 = t + calmonths(2) + caldays(35)

t2 =

Oct 01, 2014 Oct 02, 2014

t2 is also a datetime array.

Name Size Bytes Class Attributes

t2 1x2 161 datetime

In summary, there are several ways to represent dates and times, and MATLAB has a data type for each approach:

See Also

datetime | duration | calendarDuration