Search date 7 days before the current date php

2

In PHP I wanted to fetch the first day and the last day of the last 7 days. I have the current date:

$data_actula = date("Y-m-d");

Now I want to go get the dates 7 days ago. For example, today is 2014-07-29, I want to find the 2014-07-22 value. With this I must always keep in mind the changes of the months. How can I reach this value?

    
asked by anonymous 29.07.2014 / 17:46

4 answers

4

The DateTime class is much more preferable to manipulate date / time and relative:

<?php

date_default_timezone_set( 'America/Sao_Paulo' );


$time = new DateTime( '2014-07-29' );

print '<pre>'; print_r( $time ); print '</pre>';

$time -> sub( new DateInterval( 'P7D' ) );

print '<pre>'; var_dump( $time, $time -> format( 'Y-m-d' ) ); print '</pre>';

The only small drawback is the DateInterval requirement to subtract (or add) a range of time since it has a syntax a little differentiated , based on the specification ISO 8601

    
29.07.2014 / 18:17
4
<?php
   //Precisa de definir a função abaixo para evitar warnings
   date_default_timezone_set('America/Los_Angeles');
   //Sua data original
   $Date = "2014-07-29";
   //Modifica a data (7 dias atrás) 
   $data_actula = date('Y-m-d', strtotime($Date. ' - 7 days'));
   //Mostra resultado
   echo $data_actula;
?>

Note that if you want to add it is very similar:

$data_actula = date('Y-m-d', strtotime($Date. ' + 7 days'));
    
29.07.2014 / 17:54
1

You can solve this as follows:

<?php
$data_actula    = date("Y-m-d");
$danta_anterior = date("Y-m-d", strtotime($data_actula) - (7 * 24 * 60 * 60));

See running here: link

    
29.07.2014 / 18:25
1

Still, you can use DateInterval in an easier way if you're not getting used to the instantiation parameters of it, like me. Just use the DateTime::createFromDateString() method;

See:

$time = new DateTime('2014-07-29', new DateTimeZone('America/Sao_Paulo'));

print_r($time);

$time->sub(DateInterval::createFromDateString('-7 days'));

var_dump($time,$time->format( 'Y-m-d' )); 
    
28.06.2016 / 20:39