沉冰浮水

沉冰浮水

做最终到的事,成为最终成为的人!
github
bilibili
mastodon
zhihu
douban

"PHP" Get the first day (Monday) of the week in which a specific date falls.

In the Z-BlogPHP application below, the functionality of "getting the first day of a timestamp's week" is used. However, the initial implementation is not correct.

Rainy Collection - Z-Blog Application Center:

https://app.zblogcn.com/?id=21047

Initially, the intention was to directly obtain the timestamp of 00:00:00, but it turned out to be too troublesome and prone to errors.

function mz_ShikonNoTama_GetCurMonday($time)
{
  // Incorrect implementation
  // $w = date("N", $time);
  // return $time - ($time % 86400) - 86400 * ($w - 1) - 3600 * 8;

  // Correct implementation
  $week = date("N", $time);
  return $time - ($week - 1) * 86400;

  // If you really want to get 00:00, you can do it like this
  // $week = date("N", $time);
  // return $time - ($week - 1) * 86400 - (($time + 28800) % 86400);
}
$arr = [1642896000, 1642953599, 1642953600, 1642957612];
$rltHTML = '';
for ($i = 0; $i < count($arr); $i++) {
  $time = $arr[$i];
  $date = date("Y-m-d H:i", $time);
  $week = date("N", $time);
  $monday = $time - ($week - 1) * 86400;
  // $monday = $time - ($week - 1) * 86400 - (($time + 28800) % 86400);
  $rltHTML .= strtr($tpl, [
    '{key}' => 'time',
    '{value}' => $date,
  ]);
  $rltHTML .= strtr($tpl, [
    '{key}' => 'week',
    '{value}' => $week,
  ]);
  $rltHTML .= strtr($tpl, [
    '{key}' => 'monday',
    '{value}' => date("Y-m-d H:i", $monday),
  ]);
  $rltHTML .= "<br>";
}

echo $rltHTML;

// N	               丨 ISO-8601 format number of the day of the week 丨 1 (for Monday) to 7 (for Sunday)
// w	               丨 Numeric representation of the day of the week	            丨 0 (for Sunday) to 6 (for Saturday)
// D	               丨 A textual representation of a day, three letters     丨 Mon to Sun
// l (lowercase 'L') 丨 A full textual representation of the day of the week 丨 Sunday to Saturday
time: 2022-01-23 08:00

week: 7

monday: 2022-01-17 08:00


time: 2022-01-23 23:59

week: 7

monday: 2022-01-17 23:59


time: 2022-01-24 00:00

week: 1

monday: 2022-01-24 00:00


time: 2022-01-24 01:06

week: 1

monday: 2022-01-24 01:06
Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.