219 of 410 menu

The date_sub Function

The date_sub function allows subtracting an interval from a date. It accepts two parameters: a date object created via date_create and an interval created via date_interval_create_from_date_string.

Syntax

date_sub($date, $interval);

Example

Subtract 2 weeks from the current date:

<?php $date = date_create('2023-12-01'); $interval = date_interval_create_from_date_string('2 weeks'); date_sub($date, $interval); echo date_format($date, 'Y-m-d'); ?>

Code execution result:

'2023-11-17'

Example

Subtract 3 months and 5 days from the specified date:

<?php $date = date_create('2023-08-20'); $interval = date_interval_create_from_date_string('3 months + 5 days'); date_sub($date, $interval); echo date_format($date, 'Y-m-d'); ?>

Code execution result:

'2023-05-15'

See Also

  • the date_add function,
    which adds an interval to a date
  • the date_create function,
    which creates a DateTime object
  • the date_diff function,
    which calculates the difference between dates
byenru