我是一名當前註冊PHP課程的學生,我們的教師已經告訴我們要創建可以接受用戶生日的代碼,然後計算從今天起有多少天是他們下一個生日。我完全理解如何計算兩個日期之間的時間,但由於我只需要用戶生日之前的天數,所以它變得棘手。我已經搜索了這個問題,但所有的答案似乎只是計算兩年之間的時間。我需要計算直到用戶下一個生日的時間
例如:
輸入:1985年11月14日
今天的日期是2016年11月9日
輸出(應該是): 「你有5天,直到你的下一個生日」
THIS IS MY編輯的代碼:
<?php
$johnsBirthday = $_GET ['JohnBday'];
$jakesBirthday = $_GET ['JakeBday'];
$john_bday = new DateTime($_GET['JohnBday']);
$jake_bday = new DateTime($_GET['JakeBday']);
$today_date = new DateTime();
switch (true) {
case ($john_bday < $today_date) :
$today_date->setDate($john_bday->format('Y'), $today_date- >format('m'), $today_date->format('d'));
break;
case ($today_date < $john_bday) :
$john_bday->setDate($today_date->format('Y'), $john_bday->format('m'), $john_bday->format('d'));
break;
}
switch (true) {
case ($today_date < $jake_bday) :
$jake_bday->setDate($today_date->format('Y'), $jake_bday->format('m'), $jake_bday->format('d'));
break;
case ($jake_bday < $today_date) :
$jake_bday->setDate($today_date->format('Y'), $jake_bday->format('m'), $jake_bday->format('d'));
break;
}
$john_interval = $john_bday->diff($today_date);
$john_diff = $john_interval->format('%a');
echo "John you have $john_diff days until your next Birthday</br>";
$jake_interval = $jake_bday->diff($today_date);
$jake_diff = $jake_interval->format('%a');
echo "Jake you have $jake_diff days until your next Birthday</br>";
if ($johnsBirthday < $jakesBirthday)
{
echo "John is older than Jake</br>";
}
elseif ($johnsBirthday > $jakesBirthday)
{
echo "Jake is older than John</br>";
}
else
{
echo "Jake and John are twins";
}
?>
感謝提前的幫助下, 蒂芙尼
所以我編輯爲你指示的代碼,但是當我運行此程序計算的天數是有點過。所以如果生日真的是30天以後,該計劃可能會讓我有33天的時間。 – Veronica
@TiffanyIwinyoulose檢查我的編輯,我猜你錯過了第二個'switch'語句中的'$ jake_bday' :) –