我有一周和一周的周数,我怎么能用PHP获取日期

时间:2014-02-17 13:52:09

标签: php

我有一周的一周和一周的工作日,我需要得到确切的日期。

这是我到目前为止所尝试的。我在堆栈溢出时发现了这个代码,但它不准确:

function required_date($week_num, $day) {
  $week_of_year = sprintf('%02d', date('W', strtotime(date('Y-m-01'))) + $week_num);
  $day_of_week  = date('N', strtotime($day));
  $timestamp    = strtotime(date('Y') . '-W' . $week_of_year . '-' . $day_of_week);

  return $timestamp;
}


$timestamp = required_date(8, 'wednesday');
echo date('Y-m-d', $timestamp);

输出: 2014年3月26日

预期输出 根据日程表,第8周和第三天的日期为2014-02-19。

2 个答案:

答案 0 :(得分:0)

好吧,我自己想出来了,这是代码:

function getWeekDates($week, $year)
{

    $time = strtotime("1 January $year", time());
    $day = date('w', $time);
    $time += ((7*$week)+1-$day)*24*3600;
    // date on monday for the week 
    $return["Monday"] = date('Y-n-j', $time);
    $time += 1*24*3600;
    // date on tuesday for the week 
    $return["Tuesday"] = date('Y-n-j', $time);
    $time += 1*24*3600;
    // date on wednesday for the week 
    $return["Wednesday"] = date('Y-n-j', $time);
    $time += 1*24*3600;
    // date on thursday for the week 
    $return["Thursday"] = date('Y-n-j', $time);
    $time += 1*24*3600;
    // date on friday for the week 
    $return["Friday"] = date('Y-n-j', $time);
    $time += 1*24*3600;
    // date on Saturday for the week 
    $return["Saturday"] = date('Y-n-j', $time);
    $time += 1*24*3600;
    // date on Sunday for the week 
    $return["Sunday"] = date('Y-n-j', $time);

    // Returning Array containing all the dates for the days of that specific week of the year.
    return $return;
}
// Lets assume I need dates for week number 7 of the year 2014.
print_r (getWeekDates(7, 2014));

答案 1 :(得分:0)

您还可以使用 strtotime 功能。我曾经这样做过如下::

<?php

   function required_date($week_num, $day) {
    // get the present week number: exp: 8 
$presentWeek = date("W", strtotime("now"));  

    // get the present day number : exp: 2
$presentDay = date("w", strtotime("now")); 

    // convert the given day string into number
$givenDay = date("w", strtotime("{$day}"));

    // subtract two value of week number
$week = $week_num - $presentWeek;

    // subtract two value of day number
$day = $givenDay - $presentDay;

    // get the value
$timestamp = strtotime(" $week week $day day");
return $timestamp;
 }


 $timestamp = required_date(14, 'wednesday');
 echo date('Y-m-d', $timestamp);

?>