如何从“我所知道的”获得一个月的一天?

时间:2014-02-01 00:36:44

标签: php date

这里需要一些逻辑:

需要获取某一天的日期(“d”)

我所知道的:

$year = 2013;
$month = 10;
$week_nr_of_month = 3; // from 1 to 6 weeks in month
$day_of_week = 0; // Sunday date("w")

感谢逻辑

结果必须是:10月13日

2 个答案:

答案 0 :(得分:0)

strtotime可能会有所帮助。现在无法测试,但是......

$ordinal = array("first","second","third","fourth","fifth");
$weekdays = array("monday","tuesday","wednesday","thursday","friday","saturday","sunday");
$timestamp = strtotime($year."-".$month." ".$ordinal[$week_nr_of_month]." ".$weekdays[$day_of_week]);

答案 1 :(得分:0)

这很有趣。

<?php

$year = 2013;
$month = 10;
$week_nr_of_month = 3; // from 1 to 6 weeks in month
$day_of_week = 0; // Sunday date("w")

$start = new DateTime();
$start->setDate($year, $month, '1');
$end = clone $start;
$end->modify('last day of this month');
$interval = new DateInterval('P1D');
$period = new DatePeriod($start, $interval, $end);

foreach ($period as $date) {
    if ($date->format('w') == $day_of_week) {
        $wom = week_of_month($date->format('Y-m-d'));
        if ($week_nr_of_month == $wom) {
            echo $date->format('Y-m-d');
        }
    }
}

function week_of_month($date) {
    $dt = new DateTime($date);
    $bg = clone $dt;
    $bg->modify('first day of this month');
    $day_of_first = $bg->format('N');
    $day_of_month = $dt->format('j');
    return floor(($day_of_first + $day_of_month - 1) / 7) + 1;
}

See it in action

使用this answer获取灵感来获取日期的周数。