Get 30 days back date along with time

喜你入骨 提交于 2019-12-06 03:49:35

问题


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


回答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'));



回答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');



回答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;



回答4:


I know you said with PHP, however, I can't imagine not getting the records from a DB. If you want to do so from the DB,use:

$sql='SELECT * FROM myTable WHERE  date > CURRENT_DATE - INTERVAL 30 DAY';
$pdo->query($sql);



回答5:


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;
?>



回答6:


Try:
echo date("Y-m-d h:i:s",strtotime('-30 days'));

For more detail click here




回答7:


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



来源:https://stackoverflow.com/questions/26044844/get-30-days-back-date-along-with-time

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!