开发者

Given a time, how can I find the time one month ago

开发者 https://www.devze.com 2022-12-15 05:43 出处:网络
Given a time, how can 开发者_运维问答I find the time one month ago.strtotime( \'-1 month\', $timestamp );

Given a time, how can 开发者_运维问答I find the time one month ago.


strtotime( '-1 month', $timestamp );

http://php.net/manual/en/function.strtotime.php


In php you can use strtotime("-1 month"). Check out the documentation here: http://ca3.php.net/strtotime


We can achieve same by using PHP's modern date handling. This will require PHP 5.2 or better.

// say its "2015-11-17 03:27:22"
$dtTm = new DateTime('-1 MONTH', new DateTimeZone('America/Los_Angeles')); // first argument uses strtotime parsing
echo $dtTm->format('Y-m-d H:i:s'); // "2015-10-17 03:27:22"

Hope this adds some more info for this question.


<?php

$date = new DateTime("18-July-2008 16:30:30");
echo $date->format("d-m-Y H:i:s").'<br />';

date_sub($date, new DateInterval("P1M"));
echo '<br />'.$date->format("d-m-Y").' : 1 Month';

?> 


PHP 5.2=<

$date = new DateTime(); // Return Datetime object for current time
$date->modify('-1 month'); // Modify to deduct a month (Also can use '+1 day', '-2 day', ..etc)
echo $date->format('Y-m-d'); // To set the format 

Ref: http://php.net/manual/en/datetime.modify.php


This code is for getting 1 month before not 30 days

$date = "2016-03-31";

$days = date("t", strtotime($date));

echo  date("Y-m-d", strtotime( "-$days days", strtotime($date) ));


These answers were driving me nuts. You can't subtract 31 days and have a sane result without skipping short months. I'm presuming you only care about the month, not the day of the month, for a case like filtering/grouping things by year and month.

I do something like this:

$current_ym = date('ym',strtotime("-15 days",$ts));

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号