steven
steven

Reputation: 13547

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

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

Upvotes: 6

Views: 16633

Answers (7)

poleguy
poleguy

Reputation: 585

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

Upvotes: 0

Davit Huroyan
Davit Huroyan

Reputation: 302

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

Upvotes: 1

Sadee
Sadee

Reputation: 3180

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

Upvotes: 1

TheMohanAhuja
TheMohanAhuja

Reputation: 1875

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.

Upvotes: 3

Kirill V. Lyadvinsky
Kirill V. Lyadvinsky

Reputation: 99605

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

?> 

Upvotes: 1

Galen
Galen

Reputation: 30170

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

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

Upvotes: 17

justinl
justinl

Reputation: 10548

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

Upvotes: 3

Related Questions