I have this line of code

$date=new \DateTime('now');

From that date, I need to recover date of the Monday at the beginning of the week.

For example when $date=14_05_2014 19:12:20 (14 May 2014), I need a variable that has the value for the corresponding Monday: $n=12_05_2014 08:00:00 (12 May 2014).

有帮助吗?

解决方案

It's fairly easy given the powerful date/time functions in PHP:

$now = new \DateTime('now');

# "1" means "Monday", you could improve this by detecting localized settings
$daysToMove = (int)($now->format('N')) - 1; // 

# How many days to subtract?
if ($daysToMove){
    $now->sub(new \DateInterval('P' . $daysToMove . 'D'));
}

echo "Start of the week: " . $now->format('Y-m-d');

Simple explanation:

  1. you calculate current day of the week. This value can be in range 1..7.
  2. Since, Monday is 1, subtract 1 from calculated number.
  3. If resulting number of greater that 0 (meaning "today is not Monday"), create DateInterval and subtract it from current date.

You can find more about DateTime and DateInterval classes: here. Look for Examples section...

PHP date(): date

PHP DateTime (OOP variant): DateTime

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top