Php date отнять день

Вычесть дату из даты [дубликат]

Если правильно понял, Вам нужно из одной даты отнять другую. Если так то попробуйте:

$diference = strtotime($salee) - strtotime($saled); // разница между двумя датами в секундах $minutes = $diference / 60; // секунды в минутах $hours = $diference / 3600; // секунды в часах $days = $diference / 86400; // секунды в сутках 

А Вам это точно нужно? :)) Просто смотрите если из текущей даты отнять дату прошлого года, то год полученной даты будет 1. Объясните подробнее зачем Вам это нужно, может быть если более правильные решения чем отнять дату.

Количество секунд не позволяет корректно получить интервалы, начиная с месяцев. Количество суток получить почти можно(есть нюансы с переводами часов, високосными секундами и т.п.).

Создайте для каждой даты объект DateTime . Воспользуйтесь методом DateTime::diff() для получения объекта DateInterval , описывающего разность между датами. Разность между двумя датами в неделях, днях, часах, минутах и секундах.

// 19:32:56, 10 мая 1965 года $first = new DateTime("1965-05-10 7:32:56pm", new DateTimeZone('America/New_York')); // 4:29:11, 20 ноября 1962 года $second = new DateTime("1962-11-20 4:29:11am", new DateTimeZone('America/New_York')); $diff = $second->diff($first); printf("The two dates have %d weeks, %s days, " . "%d hours, %d minutes, and %d seconds " . "elapsed between them.", floor($diff->format('%a') / 7), $diff->format('%a') % 7, $diff->format('%h'), $diff->format('%i'), $diff->format('%s')); 
The two dates have 128 weeks, 6 days, 15 hours, 3 minutes, and 45 seconds elapsed between them. 

Также отвечая на вопрос в комментариях: «как получить в формате «Y-m-d h:i» — функция date http://php.net/manual/ru/function.date.php

Читайте также:  Php output in utf 8

Источник

DateTimeImmutable::sub

Возвращает новый объект DateTimeImmutable , в котором указанный объект DateInterval вычитается из указанного объекта DateTimeImmutable.

Список параметров

Только для процедурного стиля: объект DateTime , возвращаемый date_create() . Функция изменяет этот объект.

Возвращаемые значения

Возвращает новый объект DateTimeImmutable с модифицированными данными.

Примеры

Пример #1 Пример использования DateTimeImmutable::sub()

$date = new DateTimeImmutable ( ‘2000-01-20’ );
$newDate = $date -> sub (new DateInterval ( ‘P10D’ ));
echo $newDate -> format ( ‘Y-m-d’ ) . «\n» ;
?>

Результат выполнения данных примеров:

Пример #2 Дополнительный пример DateTimeImmutable::sub()

$date = new DateTimeImmutable ( ‘2000-01-20’ );
$newDate = $date -> sub (new DateInterval ( ‘PT10H30S’ ));
echo $newDate -> format ( ‘Y-m-d H:i:s’ ) . «\n» ;

$date = new DateTimeImmutable ( ‘2000-01-20’ );
$newDate = $date -> sub (new DateInterval ( ‘P7Y5M4DT4H3M2S’ ));
echo $newDate -> format ( ‘Y-m-d H:i:s’ ) . «\n» ;
?>

Результат выполнения данного примера:

2000-01-19 13:59:30 1992-08-15 19:56:58

Пример #3 Будьте осторожны при вычитании месяцев

$date = new DateTimeImmutable ( ‘2001-04-30’ );
$interval = new DateInterval ( ‘P1M’ );

$newDate1 = $date -> sub ( $interval );
echo $newDate1 -> format ( ‘Y-m-d’ ) . «\n» ;

$newDate2 = $newDate1 -> sub ( $interval );
echo $newDate2 -> format ( ‘Y-m-d’ ) . «\n» ;
?>

Результат выполнения данного примера:

Смотрите также

  • DateTimeImmutable::add() — Возвращает новый объект с добавленным количеством дней, месяцев, лет, часов, минут и секунд
  • DateTimeImmutable::diff() — Возвращает разницу между двумя объектами DateTime
  • DateTimeImmutable::modify() — Создаёт новый объект с изменённой временной меткой

User Contributed Notes

Источник

PHP: Subtract days from a date.

In this tutorial, we will show you how to subtract days, weeks, or months from a date using PHP.

To do this, we can use the strtotime function or the DateTime object.

How to subtract one day from a date using PHP.

To get yesterday’s date, you can pass in the string “yesterday” to the strtotime function like so:

//Yesterday $yesterday = date("Y-m-d", strtotime("yesterday")); //On 2019-08-19, this resulted in 2019-08-18 echo $yesterday;

Passing in the string “yesterday” to strtotime is basically the exact same thing as subtracting “-1 day” from today’s date.

Here is a DateTime alternative, which you can use if your PHP version is 5.3.0 or above:

//New DateTime object representing today's date. $currentDate = new DateTime(); //Use the sub function to subtract a DateInterval $yesterdayDT = $currentDate->sub(new DateInterval('P1D')); //Get yesterday's date in a YYYY-MM-DD format. $yesterday = $yesterdayDT->format('Y-m-d'); //Print it out. echo $yesterday;

PHP introduced the DateInterval object in version 5.3.0. This object represents a date interval.

In the example above, we set the DateInterval object to P1D, which means a period of one day. We then subtracted that interval from the current date.

If you would like to subtract five days instead of one day, then you can use P5D instead of P1D.

If you want to subtract a day from a given date:

//Pass the date you want to subtract from in as //the $time parameter for DateTime. $currentDate = new DateTime('2019-01-01'); //Subtract a day using DateInterval $yesterdayDT = $currentDate->sub(new DateInterval('P1D')); //Get the date in a YYYY-MM-DD format. $yesterday = $yesterdayDT->format('Y-m-d'); //Print it out. echo $yesterday;

In the example above, we subtracted one day from 2019-01-01. This resulted in “2018-12-31”.

Subtract 7 days.

To get last week’s date in PHP, we can use the strtotime function like so:

//7 days ago - last week. $lastWeek = date("Y-m-d", strtotime("-7 days")); //On 2019-08-19, this resulted in 2019-08-12 echo $lastWeek;

In this case, we passed “-7 days” in as a parameter to the strtotime function.

This works because the strtotime function is pretty good at parsing textual date descriptions.

Here is an alternative solution for those of you who prefer to use the DateTime object:

//Today's date. $currentDate = new DateTime(); //Subtract a day using DateInterval $lastWeekDT = $currentDate->sub(new DateInterval('P1W')); //Get the date in a YYYY-MM-DD format. $lastWeek = $lastWeekDT->format('Y-m-d'); //Print out the result. echo $lastWeek;

Above, we set “P1W” as the $interval_spec parameter for DateInterval. This translates into “a period of one week.”

If you want to subtract two weeks instead of one, then you can change “P1W” to “P2W”.

Last month / -30 days.

Getting last month’s date can be tricky. This is because the number of days in a month can vary.

For example, the month of October has 31 days, while September has 30.

Take the following example:

//Last month $lastMonth = date("Y-m-d", strtotime("-1 month")); //On 2019-08-19, this resulted in 2019-07-19 echo $lastMonth;

The snippet above will work in most situations.

However, on October 31st, the function will actually return “October 1st” instead of “September 30th”.

This is because PHP’s strtotime function treats “-1 month” the same as “-30 days.”

If you want to get the previous month’s name or number, then you will need to use the following code instead:

//Get the first date of the previous month. echo date("Y-m-d", strtotime("first day of previous month"));

If you run the script above on October 31st, it will return September 1st.

As you can see, dealing with dates can be very tricky.

Источник

date_sub

Вычитает из времени объекта DateTime заданный интервал DateInterval.

Список параметров

Только для процедурного стиля: Объект DateTime, возвращаемый date_create() . Функция изменяет этот объект.

Возвращаемые значения

Возвращает объект DateTime для применения в цепи методов или FALSE в случае возникновения ошибки.

Примеры

Пример #1 Пример использования DateTime::sub()

$date = new DateTime ( ‘2000-01-20’ );
$date -> sub (new DateInterval ( ‘P10D’ ));
echo $date -> format ( ‘Y-m-d’ ) . «\n» ;
?>

$date = date_create ( ‘2000-01-20’ );
date_sub ( $date , date_interval_create_from_date_string ( ’10 days’ ));
echo date_format ( $date , ‘Y-m-d’ );
?>

Результат выполнения данных примеров:

Пример #2 Другие примеры DateTime::sub()

$date = new DateTime ( ‘2000-01-20’ );
$date -> sub (new DateInterval ( ‘PT10H30S’ ));
echo $date -> format ( ‘Y-m-d H:i:s’ ) . «\n» ;

$date = new DateTime ( ‘2000-01-20’ );
$date -> sub (new DateInterval ( ‘P7Y5M4DT4H3M2S’ ));
echo $date -> format ( ‘Y-m-d H:i:s’ ) . «\n» ;
?>

Результат выполнения данного примера:

2000-01-19 13:59:30 1992-08-15 19:56:58

Пример #3 Будьте внимательны при вычитании месяцев

$date = new DateTime ( ‘2001-04-30’ );
$interval = new DateInterval ( ‘P1M’ );

$date -> sub ( $interval );
echo $date -> format ( ‘Y-m-d’ ) . «\n» ;

$date -> sub ( $interval );
echo $date -> format ( ‘Y-m-d’ ) . «\n» ;
?>

Результат выполнения данного примера:

Примечания

При работе с PHP 5.2 в качестве альтернативы можно использовать функцию DateTime::modify() .

Смотрите также

  • DateTime::add() — Добавляет заданное количество дней, месяцев, лет, часов, минут и секунд к объекту DateTime
  • DateTime::diff() — Возвращает разницу между двумя DateTime объектами
  • DateTime::modify() — Изменение временной метки

Источник

Оцените статью