Joppo
Joppo

Reputation: 729

How to determine start (date) of previous month in a time loop?

The php code below describes a simulated time loop in which some actions must take place.

How to determine -for this time loop- the start date (sql format) of the previous month? (If it would have been reel time (no simulation) I noticed a solution (How to find the start and end date of a previous month in PHP) )

$maxdays = 366;
$startthismonth_sql;
for($daynumber=0;$daynumber<$maxdays;$daynumber++){

  $currentdayval = "+".(string)($daynumber-$maxdays)." days";
  $date_sql = date("Y-m-d",strtotime($currentdayval)); //current date

  if($daynr != 1){
    $startthismonth_sql = date("Y-m-01",strtotime($currentdayval));
  }

  //$startpreviousmonth_sql = ??? //format yyyy-mm-dd

  //do some simulation stuff

}//for($daynumber=0;$daynumber<$maxdays;$daynumber++)

Upvotes: 1

Views: 142

Answers (3)

Jon
Jon

Reputation: 437376

Quite easy:

$reference = strtotime('+70 days'); // this is what your simulation uses
$ts = strtotime('first day of last month', $reference);
echo date('Y-m-d', $ts);

The above code would show the first day of the month preceding the month 70 days from today in the specified format.

Upvotes: 2

Michael Butler
Michael Butler

Reputation: 6309

Assuming the start of THIS month is correctly strtotime($currentdayval), the start of the previous month is:

strtotime('-1 month', strtotime($currentdayval))

That gives you the timestamp. All we're doing is subtracting 1 month from a given timestamp.

Upvotes: 1

ToBe
ToBe

Reputation: 2681

You might want to checkout mktime()

http://de3.php.net/manual/en/function.mktime.php

You can give date("n") - 1 as month value to this function. It will even allow a negative month here and calculate the appropriate month from year before itself.

Upvotes: 0

Related Questions