Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get a DateTime for one week ago

Tags:

php

datetime

I want to get the DateTime of one week ago to use it in a query. So I've done:

$date = new DateTime();
$date->sub(new DateInterval('P7D'));
$date = $date->format('Y-m-d H:i:s');

But for some reason this is not working right. Any idea of what I'm doing wrong?

like image 437
Manolo Avatar asked Apr 30 '14 00:04

Manolo


1 Answers

DateTime::sub() returns a new DateTime object. It doesn't change the original object at all.

$date = new DateTime();
$newdate = $date->sub(new DateInterval('P7D'));
$date = $newdate->format('Y-m-d H:i:s');

Demo

If you want to do this a little simpler:

$date = new DateTime('-1 week');
$date = $date->format('Y-m-d H:i:s');

Demo

like image 144
John Conde Avatar answered Sep 28 '22 06:09

John Conde