PHP:接受生日日期作为参数并返回今年的星期几的函数


PHP: Function that accepts a birthday date as a parameter and returns the day of the week from this year

从表单中提交日期(例如:1982-05-20),并返回今年的星期几。

1) 提交表格日期:

<form action="Date2.php" method="post" align="center">
    <input name="date" size="20" placeholder="yyyy-mm-dd" type="text" required="">
    <input name="submit" value="Submit" type="submit" id="submit" />
</form>

2) PHP部分:创建一个函数,该函数接受日期作为参数(来自表单)并返回一周中的哪一天(星期一或星期二等)。函数将在以下代码中使用:

<?
//How many dates do you need to put in the array????
$datearray = array("1/1/2016", "date", "date",......);
foreach ($datearray as $key => $date) {
    echo(myDateFunction($date));
}
?>

这里是获取当天名称的函数。请注意,如果出现错误,它将抛出一个异常。

function fetchDay($date)
{
    return (new DateTime($date))->format('l');
}

例如,fetchDay('2016-04-02')将返回"Saturday"

获取当前年份的一天的函数

function fetchDay($date)
{
    $dateTime = new DateTime($date);
    $currentYear = date('Y');
    $month = $dateTime->format('m');
    $day = $dateTime->format('d');
    if(!checkdate($month, $day, $currentYear))
    {
        throw new Exception('Invalid Gregorian date');
    }
    $dateTime->setDate($currentYear, $month, $day);
    return $dateTime->format('l');
}