简体   繁体   中英

Get a week ago from given date PHP

I have a monthly bill table that stored where customer need to pay the bill in Ymd format, i need to send an email notification a week before this due date. for example:

public function cronSendNotif($transaction){
  $dueDate = $transaction->getDueDate(); // 2019-08-03
  $weekAgo = $this->getWeekAgoDate($dueDate); // 2019-07-27

  $this->sendEmailNotification($transaction->getId(),$weekAgo);
}

private function getWeekAgoDate($dueDate){
   // how ??
}

how can i get the week ago date in Ymd format , if i have this given date in Ymd format?

Try this:

private function getWeekAgoDate($dueDate){
  $weekAgo = date('Y-m-d', strtotime('-7 days', strtotime($dueDate)));
  return $weekAgo;
}

Using strtotime, you can simply add/subtract days, weeks etc. from a date. Example:

function getWeekAgoDate($dueDate){
   return date("Y-m-d", strtotime($dueDate . "-1 week"));
}

You can also make use of the modify function.

$weekAgo = getWeekAgoDate($dueDate);
echo $weekAgo->format('Y-m-d H:i:s');

function getWeekAgoDate(DateTime $dueDate){
   return $dueDate->modify("- 7 days");
}

Documentation: php.net/manual/en/datetime.modify.php

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM