Accelerating the pace of engineering and science

# Documentation Center

• Trial Software

## Compute Elapsed Time

### Compute Elapsed Time

This example shows how to compute the time elapsed between 8:15 a.m. and 3:45 p.m. on different days, and display the result.

Define the start and finish dates. Your data might be in date string or date vector format.

```start  = '20-Apr-2012 8:15';
finish = [2012 04 23 15 45 00];```

Convert date strings and date vectors to serial date numbers using the datenum function. Work with serial date numbers when computing elapsed time.

```start_n = datenum(start,'dd-mmm-yyyy HH:MM');
finish_n = datenum(finish);```

Subtract the start date from the finish date. Subtracting serial date numbers returns a rational number of days.

`n = finish_n - start_n`
```n =
3.3125```

The elapsed time is 3.3125 days.

Display the elapsed time in days, hours, and minutes using the datestr function.

```days = floor(n);
hrs = datestr(n, 'HH');
mins = datestr(n, 'MM');

fprintf('\n   %d days, %s hours, %s minutes\n', ...
days, hrs, mins);
```
```   3 days, 07 hours, 30 minutes
```

### Compute Future Date

You can compute future dates by adding to a date. This topic shows two ways to do this.

#### Add Days to a Serial Date Number

This example shows how to add a rational number of days to a serial date number.

The now function returns the current date in serial date number format. You can add a number to this date. For this example, add 50 days.

`futuredate = now+50`
```futuredate =
7.3500e+05```

Alternatively, the initial date might be in date string format. Convert the date to a serial date number using the datenum function.

```initialdate = datenum('21.03.2012 13:15','dd.mm.yyyy HH:MM');
```

Add a rational number of dates to the initial date. In this example, add 5.5 days.

`futuredate = initialdate + 5.5`
```futuredate =
7.3496e+05```

You can convert the future date to date string format.

`datestr(futuredate,'dd.mm.yyyy HH:MM')`
```ans =
27.03.2012 01:15```

#### Add Years, Months, Days, or Time to a Date

This example shows how to add a number of years, months, days, hours, minutes, seconds, or milliseconds to a date in serial date number format. For example, add 5 months to January 3, 2012:

Convert the date string to serial date number format.

```initialdate = datenum('03/01/2012','dd/mm/yyyy');
```

Use the addtodate function to add 5 months to the initial date.

```futuredate = addtodate(initialdate,5,'month')
```
```futuredate =
735023```

To convert the future date to a date string, use the datestr function.

`datestr(futuredate, 'dddd, mmmm dd')`
```ans =
Sunday, June 03```