Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Date Function Seven days previous

Tags:

date

php

I am trying to use PHP's Date Function to get the date of 7 days earlier in YYYY-MM-DD format.

date('Y-m-d'); 

when i try

date('Y-m-d-7'); 

i get an error

like image 566
Harsha M V Avatar asked May 29 '12 11:05

Harsha M V


People also ask

How do I add 7 days to a date?

Just do: $date = strtotime("+7 day"); echo date('M d, Y', $date);

What is Strtotime PHP?

The strtotime() function parses an English textual datetime into a Unix timestamp (the number of seconds since January 1 1970 00:00:00 GMT). Note: If the year is specified in a two-digit format, values between 0-69 are mapped to 2000-2069 and values between 70-100 are mapped to 1970-2000.

What does date () do in PHP?

The date() function formats a local date and time, and returns the formatted date string.


2 Answers

Use the strtotime method provided by PHP.

date('Y-m-d', strtotime('-7 days'))

Thanks to @lonesomeday for pointing out my mistake in the comments ;)

like image 67
Gavin Avatar answered Sep 21 '22 06:09

Gavin


With this, as with all PHP date stuff, it's nicer to use the DateTime class.

$date = new DateTime('7 days ago'); echo $date->format('Y-m-d'); 
like image 38
lonesomeday Avatar answered Sep 25 '22 06:09

lonesomeday