Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to get 4-days ago to now - php

Tags:

php

If current date is 2016-03-06, I would like to get these dates :

2016-03-06
2016-03-05
2016-03-04
2016-03-03

I'm trying to get this purpose but my result not what I want :

$_4date = date("y-m-d",strtotime("day"));
$_3date = date("y-m-d",strtotime("-1 day"));
$_2date = date("y-m-d",strtotime("-2 day"));
$_1date = date("y-m-d",strtotime("-3 day"));

echo $_4date;
echo '<br />';
echo $_3date;
echo '<br />';
echo $_2date;
echo '<br />';
echo $_1date;

the result is :

70-01-01
16-03-05
16-03-04
16-03-03
like image 229
S.M_Emamian Avatar asked Mar 06 '16 11:03

S.M_Emamian


3 Answers

To get today's date with strtotime, you do strtotime("today");. However, as Bjorn has commented, you can simply just call date() directly.

Furthermore, the reason you are not getting the year in four digits is because you are using a lowercase y instead of an uppercase Y.

Try date("Y-m-d", strtotime("-1 day"));.

The following piece of code illustrates the required changes:

$today = date("Y-m-d");
$yesterday = date("Y-m-d", strtotime("-1 day"));

echo "$today <br />";
echo "$yesterday <br />";

// Output
2016-03-06 
2016-03-05

For more informtation, please consult the PHP documentation on the date function. It actually shows you that what to expect from y and Y and it also shows you that the default value that is passed as the second argument is time(), meaning the default is the current time.

PHP's strtotime documentation can be consulted for more information on the strtotime() function and its possible parameters.

Always check the (PHP) documentation first before asking a question.

like image 126
Thijs Riezebeek Avatar answered Sep 28 '22 07:09

Thijs Riezebeek


You need to use like that:

$_4date = date("Y-m-d"); 
$_3date = date("Y-m-d",strtotime("-1 day")); 

$_2date = date("Y-m-d",strtotime("-2 day")); 
$_1date = date("Y-m-d",strtotime("-3 day"));

Explanation:

For current date no need to use use strtotime().

For full year you need to use this format Y-m-d. y-m-d will return you the date 16-03-06 but Y-m-d will return you 2016-03-06.

like image 21
devpro Avatar answered Sep 28 '22 05:09

devpro


Use a for loop with strtotime( "... days ago" ):

for( $i = 0; $i < 4; $i++ )
{
    echo date( 'Y-m-d', strtotime( "$i days ago" ) ) . PHP_EOL;
}

The first loop (0 days ago) will output today date, other loops will output past days.

eval.in demo

like image 45
fusion3k Avatar answered Sep 28 '22 07:09

fusion3k