Get 30 days back date along with time

34,936

Solution 1

The problem is likely caused by the malformed date() call. The first argument passed to date() should be the format (as shown in the Docs) and the second should be an optional timestamp.

Try this:

$d2 = date('c', strtotime('-30 days'));

PHPFiddle


As a short aside, the whole snippet can be simplified as follows:

$url = $row["url"];
$pageid = getPageID($url);
$date = date('y-m-d g:i');
$d1 = time();
$d2 = date('y-m-d g:i', strtotime('-30 days'));

Solution 2

You can also use the DateTime class's sub() method together with an DateInterval:

$now = new DateTime();
$back = $now->sub(DateInterval::createFromDateString('30 days'));
echo $back->format('y-m-d g:i');

Solution 3

if you would like to get out put as 2014-08-01 then try the below code. thanks

$date = '2014-08-30 23:06';
$new_date = date('Y-m-d G:i', strtotime($date.' - 29 days'));
echo "30 days back is " . $new_date;

Solution 4

From your brief description and example given, I believe that you want the date to be 30 days back and time to be the same as of now. The below code will serve this purpose. Thanks.

<?php
$date=date('y-m-d g:i');
$time=date('g:i');
echo "Todays date:" . $date. "<br>";
$d2 = date('y-m-d', strtotime('-30 days'));
echo "30 days back:" . $d2 . ' ' .$time;
?>

Solution 5

Very simple two lines of code $date = new DateTime(); echo $date->modify('-30 day')->format('y-m-d g:i');

Share:
34,936
Mumbai CabinCrew
Author by

Mumbai CabinCrew

Updated on July 15, 2022

Comments

  • Mumbai CabinCrew
    Mumbai CabinCrew almost 2 years

    I want to calculate EXACT past 30 days time period in php from now (for example 30 aug 14 23:06) to 30 days back (for example 1 aug 14 23:06). I wrote this where current datetime goes in $d1 and past 30 days datetime goes in $d2 but somehow i am not getting correct results. Any idea?

    $url=$row["url"];
    $pageid=getPageID($url);
    $date=date('y-m-d g:i');
    $d1=strtotime($date);
    $d2=date(strtotime('today - 30 days'));
    

    Thanks

    • Mike
      Mike over 9 years
      What results are you getting?
    • user1032531
      user1032531 over 9 years
      Are you using MySQL to get your records?
    • BenM
      BenM over 9 years
      strtotime('-30 days') should suffice.
    • Mike
      Mike over 9 years
      YOu can simplify $date=date('y-m-d g:i'); $d1=strtotime($date); to $date = time();
  • Mumbai CabinCrew
    Mumbai CabinCrew over 9 years
    Thanks... $d2 = date('y-m-d g:i', strtotime('-30 days')); this is what i was looking for but goofing up in syntax.