Fetch date 7 days before current php date

Asked

Viewed 2,195 times

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 get the date 7 days ago. For example, today is day 2014-07-29, I want to find the value 2014-07-22. With this I have to always keep in mind the changes of the months. How can I reach this value?

4 answers

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'));
  • That’s right. Thank you very much!

  • Although suitable to the example, without being boring, I advise the use of Datetime and Dateinterval objects if there are comparison calculations.

  • 1

    @neoprofit, I agree with what you said and at'e I find it interesting to have an answer that covers the DateTime but I thought because the question was asked using date() that the PO would like the answer while maintaining the type.

  • @Kyllopardiun you’re right!

  • I think no delay and pr[opria Datetime will come to consider the kind of argument that strtotime() accepts.

4


The class Datetime is much more preferable to handle 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 inconvenience is the requirement of the object Dateinterval to subtract (or add) a time interval because it has a syntax slightly different, specification-based ISO 8601

  • 1+ Not to be used DateTime.

1

You can solve it this way too:

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

See running here: http://3v4l.org/0CVHY

1

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

Behold:

$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' )); 

Browser other questions tagged

You are not signed in. Login or sign up in order to post.