PHP weekdays of current week, why is date() and strtotime taking next week?

做~自己de王妃 提交于 2019-12-07 11:52:44

问题


I am using the following code to get a Y-m-d format of weekdays:

$monday = date('Y-m-d', strtotime('Monday'));
$tuesday = date('Y-m-d', strtotime('Tuesday'));
$wednesday = date('Y-m-d', strtotime('Wednesday'));
$thursday = date('Y-m-d', strtotime('Thursday'));
$friday = date('Y-m-d', strtotime('Friday'));

Today is 2012-08-01 (week 31) the Monday value I need should be 2012-07-30.

How come strtotime('Monday') makes it next monday?


回答1:


Because date('Y-m-d') returns today's date i.e.., month of august. And you are converting monday to time. now that time is represented in terms of date(Y-m-d) (august of 2012).. So the obvious answer would be the next coming monday starting from today.

So to get last week's date,use

$monday=date(Y-m-d,strtotime('monday this week'))



回答2:


For my application I needed to just create variables for the dates of the current week.

That's why I went along with this code:

$mon_value= date('Y-m-d', strtotime('Monday this week'));
$tue_value= date('Y-m-d', strtotime('Tuesday this week'));
$wed_value= date('Y-m-d', strtotime('Wednesday this week'));
$thu_value= date('Y-m-d', strtotime('Thursday this week'));
$fri_value= date('Y-m-d', strtotime('Friday this week'));



回答3:


It alway return next day of the type. Next monday is 08-06, and next thursday is 08-02.

<?php
  function getDateOfWeekDay($day) {
    $weekDays = array(
      'Sunday',
      'Monday',
      'Tuesday',
      'Wednesday',
      'Thursday',
      'Friday',
      'Saturday',
    );

    $dayNumber = array_search($day, $weekDays);
    $currentDayNumber =  date('w', strtotime('today'));

    if ($dayNumber > $currentDayNumber) {
      return date('Y-m-d', strtotime($day));
    } else {
      return date('Y-m-d', strtotime($day) - 604800);
    }
  }

  echo  getDateOfWeekDay('Monday');
?>


来源:https://stackoverflow.com/questions/11756351/php-weekdays-of-current-week-why-is-date-and-strtotime-taking-next-week

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!