I have 2 input fields for birth dates. I would like to then calculate days until the next birthday for each individual and the difference between both dates entered to determine who is older. Is my syntax logical/where did i go wrong?
<form>
John's Birthday (YYYY-MM-DD):
<input type=text name=jhbd value=0><br> Jake's Birthday (YYYY-MM-DD):
<input type=text name=jkbd value=0><br>
<input type=submit>
</form>
$john_bd = $_POST['jhbd'];
$jake_bd = $_POST['jkbd'];
$today = date("Y/m/d");
$interval_jh = $john_bd ->diff($today);
$interval_jk = $jake_bd ->diff($today);
echo "There are".$interval_jh->days."days until John's birthday ";
echo "There are".$interval_jk->days."days until Jake's birthday ";
if ($john_bd > $jake_bd) {
echo "John is older";
} else if ($jake_bd > $john_bd) {
echo "Jake is older";
} else {
echo "Both Jake and John are twins!";
}
You need to convert them first.
$today = time();
$your_date = strtotime($john_bd);
$datediff = $now - $john_bd;
echo floor($datediff/(60*60*24));
it might help you
Your variant is almost correct. Use format for show diff between dates. Like in example
$origin = new DateTime('2009-10-11');
$target = new DateTime('2009-10-13');
$interval = $origin->diff($target);
echo $interval->format('%R%a days');
public function days_to_birth(string $date) : int {
if(empty($date))
{
return -1;
}
if($date == '0000-00-00')
{
return -1;
}
$ts = strtotime($date.' 00:00:00');
$bY = date('Y',$ts);
$bm = date('m',$ts);
$bd = date('d',$ts);
$nowY = date('Y');
$nowm = date('m');
$nowd = date('d');
if($bm == $nowm && $bd >= $nowd)
{
return $bd - $nowd;
}
if( ($bm == $nowm && $bd < $nowd) || ($bm < $nowm) )
{
$nextBirth = ($nowY+1).'-'.$bm.'-'.$bd;
$nextBirthTs = strtotime($nextBirth);
$diff = $nextBirthTs - time();
return floor($diff/(60*60*24));
}
if($bm > $nowm )
{
$nextBirth = $nowY.'-'.$bm.'-'.$bd.'00:00:00';
$diff = strtotime($nextBirth) - time();
return floor($diff/(60*60*24));
}
return -1;
}
Related
I have a php script here to create login at our datacenter for myself, but this script is doing the login for next week if i run it after 12:00 on monday, and a lot of times I'm not there the whole week, so I want to improve this script by asking for user input and pass the dates that I will be there so the script only picks up on those dates. I know i have to do this with stdin and I do have a part that works, but i have no idea on how to integrate this into the current script and how to make sure i can give multiple dates
My stdin part that does ask my for a date, but no idea on how to combine it:
<?php
function promptDateFromUser(string $prompt, string $dateFormat): DateTimeInterface
{
echo "{$prompt} [$dateFormat]: ";
$stdin = fopen('php://stdin', 'r');
$line = trim(fgets(STDIN));
fclose($stdin);
$dateTime = DateTimeImmutable::createFromFormat('Y-m-d', $line);
if (! $dateTime instanceof DateTimeInterface) {
throw new UnexpectedValueException('Invalid datetime format');
}
}
$dateTime = promptDateFromUser("Please insert date:", 'Y-m-d');
?>
My login script as of now:
<?php
require 'shared.php';
restore_exception_handler();
restore_error_handler();
$md = new RevisionModificationData;
$md->comment = 'Set by the dcgaccess script';
$date = new DateTime();
$hour = (int)$date->format('H');
$dow = (int)$date->format('w');
if (($dow === 1 && $hour > 12) || ($dow > 1 && $dow < 6)) {
$add = 'P' . (8 - $dow) . 'D';
$date->add(new DateInterval($add));
}
if (($dow === 1 && $hour <= 12) || $dow === 0 || $dow === 6) {
if ($dow === 6) {
$date->add(new DateInterval('P2D'));
} elseif ($dow === 0 ) {
$date->add(new DateInterval('P1D'));
}
}
$tomorrow = $date->format('Y-m-d');
$duration = 720;
$customerId = 30;
$purpose = 'DCG visit';
$phoneNumber = '';
$name = 'SOME NAME, REMOVED FOR PUBLICATION';
$colo = Colo::getByName($name);
Ensure::notNull($colo, "Colo for RackSpace is null when it should not be!");
$spaces = $colo->getRackSpaces();
foreach ($spaces as $space) {
$rackSpace = $space;
}
Ensure::notNull($rackSpace, "RackSpace is null when it should not be!");
if ($colo->getCustomerId() != $customerId) {
throw new UserException(ErrorCodes::PERMISSION_DENIED);
}
for ($x = 0; $x < 5; $x++) {
$start = $tomorrow." 8:00:00";
$end = Util::stringToMysqlDateTime($start . ' + ' . $duration . ' minutes');
$shouldSms = strlen((string)$phoneNumber) > 0;
$req = BioAccessRequest::create($rackSpace, $purpose, $start, $end, $shouldSms, $md);
$users = BioAccessUser::getAll();
foreach ($users as $user) {
if ($user->name === 'USER NAME') {
$req->addBioAccessUser($user, $md);
}
}
$req->request();
echo "Access requested for: ", $tomorrow, PHP_EOL;
$date->add(new DateInterval('P1D'));
$tomorrow = $date->format('Y-m-d');
}
?>
I'm a big php noob, so some explanation is greatly appreciated!
after some help from a friend, i managed to solve this:
#!/usr/bin/env php
<?php
include('shared.php');
restore_exception_handler();
restore_error_handler();
// Constants
$timeout = 45;
$md = new \RevisionModificationData;
$md->comment = 'Set by the dcgaccess script';
$duration = "720";
$customerId = "30";
$purpose = "DCG visit";
$phoneNumber = "";
$name="SOME NAME, REMOVED FOR PUBLICATION";
// Functions
function requestInput($msg) {
global $timeout;
echo "$msg\n\nThe timeout for this selection is $timeout seconds.\n\n> ";
$fd = fopen('php://stdin', 'r');
$read = array($fd);
$write = $except = array(); // we don't care about this
if(stream_select($read, $write, $except, $timeout)) {
$choice = trim(fgets($fd));
}
echo "\nYou typed: $choice\n\n";
return $choice;
}
// Start of program
$date = new DateTime();
$weekchoice = (int)requestInput("Which week would you like to request access for?\n1) Current week\n2) Next week\n3) Specific week number");
if ($weekchoice == 3) {
$weeknumber = (int)requestInput("Please enter a numeric week number");
} else {
$weeknumber = (int)$date->format("W");
if ($weekchoice == 2) {
$weeknumber += 1;
}
}
// We override $date with the start of the chosen week
$date->setISODate($date->format("Y"), $weeknumber);
echo "Thanks, you chose week $weeknumber which starts with " . $date->format("l d F, Y") . " \n\n";
$dayschoice = requestInput("Please enter the days you want access, as a space separated list:\n1) Monday\n2) Tuesday\n3) Wednesday\n4) Thursday\n5) Friday\n\nExample: 1 3 5");
$daylist = explode(' ', $dayschoice);
$processedDays = [];
foreach ($daylist as $eachday) {
$iday = (int)$eachday;
if ($iday == 0 || $iday % 7 == 0) { // No Sundays, also (int)"" -> 0, which is terrible
continue;
}
$add_days = $iday - 1; // Sums 0 if Monday, 1 if Tuesday and so on...
$newdate = new DateTime($date->format("Y-m-d"));
$newdate->modify("+$add_days days");
$processedDays[] = $newdate;
$formatted = $newdate->format("l d F Y");
echo "Processing day $iday, which is $formatted\n";
}
$hour = $date->format('H');
$tomorrow = $date->format('Y-m-d');
$confirm = requestInput("\nRequest access for these days? Yes/No");
if ($confirm != "Yes") {
echo 'Good bye!';
exit(0);
}
foreach ($processedDays as $reqDay) {
echo "Submitting " . $reqDay->format("l d F Y") . "\n";
$colo = Colo::getByName($name);
Ensure::notNull($colo, "Colo for RackSpace is null when it should not be!");
$spaces = $colo->getRackSpaces();
foreach ($spaces as $space) {
$rackSpace = $space;
}
Ensure::notNull($rackSpace, "RackSpace is null when it should not be!");
if ($colo->getCustomerId() != $customerId) {
throw new UserException(ErrorCodes::PERMISSION_DENIED);
}
}
foreach ($processedDays as $reqDay) {
$start = $reqDay->format('Y-m-d')." 8:00:00";
$end = Util::stringToMysqlDateTime($start . ' + ' . $duration . ' minutes');
$shouldSms = strlen((string)$phoneNumber) > 0;
$req = BioAccessRequest::create($rackSpace, $purpose, $start, $end, $shouldSms, $md);
$users = BioAccessUser::getAll();
foreach ($users as $user) {
if ($user->name === 'USER NAME') {
$req->addBioAccessUser($user, $md);
}
}
$req->request();
echo "Access requested: ", $reqDay->format('l d F Y'), PHP_EOL;
$tomorrow = $date->format('Y-m-d');
}
?>
i am trying to get number of days between two given dates, but while trying this way its not giving the number of days.
$pur_dt = date_create('2015-08-03');
$todate = date_create(date('Y-m-d'));
$diff = date_diff($todate,$pur_dt);
print_r($diff);
echo $diff->format('%R%a days');
if($diff>15) //checking condition if $pur_dt - $todate > 15
{
echo 'Hello you are not eligible';
}
else
{
echo 'eligible';
}
its not working, not giving the number of days between given two dates.
Try this. It is very simple.
<?php
$date1 = strtotime("2015-11-16 10:01:13");
$date2 = strtotime("2015-05-06 09:47:16");
$datediff = $date1 - $date2;
echo floor($datediff/(60*60*24))." days"; //output 194 days
?>
It's better using DateTime class, you can see comment(9) at PHP manual as it answer your question
Try this,
$pur_dt = date_create('2015-08-03');
$todate = date_create(date('Y-m-d'));
$datediff = $pur_dt - $todate;
$diff = $datediff/(60*60*24);
if($diff>15) //checking condition if $pur_dt - $todate > 15
{
echo 'Hello you are not eligible';
}
else
{
echo 'eligible';
}
Try This :
$pur_dt = Date('2015-08-03');
$todate = Date(date('Y-m-d'));
$pur_dt = strtotime($pur_dt);
$todate = strtotime($todate);
$seconds_diff = $todate - $pur_dt;
$$diff = floor($seconds_diff/(60*60*24));
if($diff>15) //checking condition if $pur_dt - $todate > 15
{
echo 'Hello you are not eligible';
}
else
{
echo 'eligible';
}
Try this
$pur_dt = date_create('2015-08-03');
$todate = date_create(date('Y-m-d'));
$diff = date_diff($todate,$pur_dt);
print_r($diff);
echo $diff->format('%R%a days');
if($diff->days>15) //checking condition if $pur_dt - $todate > 15
{
echo 'Hello you are not eligible';
}
else
{
echo 'eligible';
}
This code is used to take values inputted from a form but this does not take a year entered as 0100 as 0100 but as 1915, this is then used with the JS seen in one of my other questions any help here would be very good, I think the issue is something to do where the year is taken but I just can't get this to work correctly. Is this a limitation of php?
<?php
$year = "";
$month = "";
$day = "";
if (isset($_GET['year']) && !empty($_GET['year'])) {
$year = $_GET['year'];
}
if (isset($_GET['month']) && !empty($_GET['month'])) {
$month = $_GET['month'];
$monthNumber = date('m', strtotime("$month 1 Y"));
}
if (isset($_GET['day']) && !empty($_GET['day'])) {
$day = $_GET['day'];
}
if ($year != "" && $monthNumber != "" && $day != "") {
$fullUrlDate = $year . "-" . $monthNumber . "-" . $day;
$urlDate = new DateTime(date($fullUrlDate));
$today = new DateTime(date("Y-m-d H:i:s"));
$interval = $urlDate->diff($today);
$gapYears = $interval->y;
$gapMonths = $interval->m;
$gapDays = $interval->d;
$gapDaysTotal = $interval->days;
$gapWeeksTotal = round($interval->days/7);
$gapHours = $interval->h;
$gapMinutes = $interval->i;
$gapSeconds = $interval->s;
if ($gapWeeksTotal == 1) {
$gapWeeksSuffix = "";
} else {
$gapWeeksSuffix = "s";
}
if ($gapDays == 1) {
$gapDaysSuffix = "";
} else {
$gapDaysSuffix = "s";
}
$ordinalSuffix = date("S", strtotime($fullUrlDate));
if (strtotime($fullUrlDate) < strtotime(date("Y-m-d H:i:s")) ) {
$dateInThePast = true;
} else {
$dateInThePast = false;
}
// Months gap
$monthsInterval = date_diff($urlDate, $today);
$monthsGap = $monthsInterval->m + ($monthsInterval->y * 12);
$gapMonthsSuffix = ($monthsGap == 1 ? "" : "s");
DateTime has no such limitation, but the date function you use to initialise it, does. You can use DateTime::setDate to set any year you want:
php > $a = new DateTime("2015-08-24");
php > echo $a->format(DateTime::ISO8601);
2015-08-24T00:00:00+0000
php > $a->setDate(90, 8, 24);
php > echo $a->format(DateTime::ISO8601);
0090-08-24T00:00:00+0000
php > $a->setDate(90090, 8, 24);
php > echo $a->format(DateTime::ISO8601);
90090-08-24T00:00:00+0000
I have created function to generate list of members having birthday 1 week before, today and week after. The function is
$m= date("m"); // Month value
$de= date("d"); //today's date
$y= date("Y"); // Year value
for($i=0;$i<count($members);$i++){
$m_bday = strtotime($members[$i]->dob);
$bday_date = date('d',$m_bday);
$bday_month = date('m',$m_bday);
$bday = strtotime(date('Y-m-d',mktime(0,0,0,$bday_month,$bday_date,$y)));
//echo $bday_date."</br>".$bday_month."</br>".$members[$i]->dob."</br>".date('Y-m-d',$bday);exit;
$week_before = strtotime(date('Y-m-d', mktime(0,0,0,$m,($de-7),$y)));
$week_after = strtotime(date('Y-m-d', mktime(0,0,0,$m,($de+7),$y)));
if(date('d-m') == date('d-m',$bday)){
$this->present_bday[] = array('mem_name'=> $members[$i]->name);
}
else if(date('d-m',$week_before) <= date('d-m',$bday) && date('d-m',$bday) < date('d-m')){
$this->past_bday[] = array('mem_name' => $members[$i]->name);
}
else if(date('d-m')< date('d-m',$bday) && date('d-m',$bday) <= date('d-m',$week_after)){
$this->future_bday[] = array('mem_name' => $members[$i]->name);
}
}
The date format returned from the db is yyyy-mm-dd i.e 1960-06-12. This code works fine for 1 week before and today but 1 week after returning if the year is below 1970 and 1 week after condition completely fails.
Can anyone provide me with proper date manipulation for the correct results please?
I think that your trouble is because strtotime return seconds from UNIX epoch and that's actually 1970. I'd better compare dates directly in database: SELECT ADDDATE('2008-01-02', INTERVAL 1 WEEK); or SELECT SUBDATE('2008-01-02', INTERVAL 1 WEEK);
You can also do that like this:
$datetime1 = new DateTime('2009-10-11');
$datetime2 = new DateTime('2009-10-13');
$interval = $datetime1->diff($datetime2);
if((integer) $interval->format('%R%a') > 7) // More than week
Try This:
<?php
$m= date("m"); // Month value
$de= date("d"); //today's date
$y= date("Y"); // Year value
for($i=0;$i<count($members);$i++){
$mem_bod_explode=explode("-",$members[$i]->dob);
$m_bday = mktime(0,0,0,$mem_bod_explode[1],$mem_bod_explode[2],$y);
//$bday_date = date('d',$m_bday);
//$bday_month = date('m',$m_bday);
//$bday = $m_bday;
//echo $bday_date."</br>".$bday_month."</br>".$members[$i]->dob."</br>".date('Y-m-d',$bday);exit;
$week_before = mktime(0,0,0,$mem_bod_explode[1],$mem_bod_explode[2]-7,$y);
$week_after = mktime(0,0,0,$mem_bod_explode[1],$mem_bod_explode[2]+7,$y);
echo date('Y-m-d',$week_before);
echo"<br>";
echo date('Y-m-d',$week_after);
echo"<br>";
echo date('Y-m-d');
if(date('Y-m-d') == date('Y-m-d',$m_bday)){
$present_bday[] = array('mem_name'=> $members[$i]->name);
}
else if(date('Y-m-d',$m_bday)<date('Y-m-d') && date('Y-m-d',$m_bday)>=date('Y-m-d',$week_before)){
$past_bday[] = array('mem_name'=> $members[$i]->name);
}
else if(date('Y-m-d',$m_bday)>date('Y-m-d') && date('Y-m-d',$m_bday)<=date('Y-m-d',$week_after)){
$future_bday[] = array('mem_name'=> $members[$i]->name);
}
}
?>
Try This Code .Hope this will help you.
$m= date("m"); // Month value
$de= date("d"); //today's date
$y= date("Y"); // Year value
for($i=0;$i<count($members);$i++){
$mem_bod_explode=explode("-",$members[$i]->dob);
$m_bday = mktime(0,0,0,$mem_bod_explode[1],$mem_bod_explode[2],$mem_bod_explode[0]);
$bday_date = date('d',$m_bday);
$bday_month = date('m',$m_bday);
$bday = $m_bday;
//echo $bday_date."</br>".$bday_month."</br>".$members[$i]->dob."</br>".date('Y-m-d',$bday);exit;
$week_before = mktime(0,0,0,$mem_bod_explode[1],$mem_bod_explode[2]-7,$mem_bod_explode[0]);
$week_after = mktime(0,0,0,$mem_bod_explode[1],$mem_bod_explode[2]+7,$mem_bod_explode[0]);
if(date('d-m') == date('d-m',$bday)){
$this->present_bday[] = array('mem_name'=> $members[$i]->name);
}
else if(date('d-m',$week_before) <= date('d-m',$bday) && date('d-m',$bday) < date('d-m')){
$this->past_bday[] = array('mem_name' => $members[$i]->name);
}
else if(date('d-m')< date('d-m',$bday) && date('d-m',$bday) <= date('d-m',$week_after)){
$this->future_bday[] = array('mem_name' => $members[$i]->name);
}
}
Try the below code for testing:
I have putted date 1983-10-30 and its showing in Past.
<?php
$m= date("m"); // Month value
$de= date("d"); //today's date
$y= date("Y"); // Year value
for($i=0;$i<1;$i++){
$mem_bod_explode=explode("-","1983-10-30");
$m_bday = mktime(0,0,0,$mem_bod_explode[1],$mem_bod_explode[2],$y);
//$bday_date = date('d',$m_bday);
//$bday_month = date('m',$m_bday);
//$bday = $m_bday;
//echo $bday_date."</br>".$bday_month."</br>".$members[$i]->dob."</br>".date('Y-m-d',$bday);exit;
$week_before = mktime(0,0,0,$mem_bod_explode[1],$mem_bod_explode[2]-7,$y);
$week_after = mktime(0,0,0,$mem_bod_explode[1],$mem_bod_explode[2]+7,$y);
echo date('Y-m-d',$week_before);
echo"<br>";
echo date('Y-m-d',$week_after);
echo"<br>";
echo date('Y-m-d');
if(date('Y-m-d') == date('Y-m-d',$m_bday)){
$present_bday[] = array('mem_name'=> "fgfg");
}
else if(date('Y-m-d',$m_bday)<date('Y-m-d') && date('Y-m-d',$m_bday)>=date('Y-m-d',$week_before)){
$past_bday[] = array('mem_name' => "gfgfg");
}
else if(date('Y-m-d',$m_bday)>date('Y-m-d') && date('Y-m-d',$m_bday)<=date('Y-m-d',$week_after)){
$future_bday[] = array($members[$i]->name);
}
}
echo"<br>";
echo"Past Birthday:<br>";
print_r($past_bday);
echo"<br>";
echo"Present Birthday:<br>";
print_r($present_bday);
echo"<br>";
echo"Future Birthday:<br>";
print_r($future_bday);
echo"<br>";
?>
i compared the dates in database query itself came up with something like this
$res = $this->db->query("SELECT * FROM members WHERE DAYOFYEAR(curdate()) - 7 <= dayofyear(dob) AND DAYOFYEAR(curdate()) +7 >= dayofyear(dob);")->result();
$weekbfr_mem = $this->db->query("SELECT * FROM members WHERE DAYOFYEAR(curdate()) - 7 <= dayofyear(dob) AND dayofyear(dob) < DAYOFYEAR(curdate());")->result();
$bday_mem = $this->db->query("SELECT * FROM members WHERE DAYOFYEAR(curdate()) = dayofyear(dob);")->result();
$weekafter_mem = $this->db->query("SELECT * FROM members WHERE DAYOFYEAR(curdate()) < dayofyear(dob) AND dayofyear(dob) <= DAYOFYEAR(curdate()+7);")->result();
the main disad in this i have to make 3 query to server its slow for project.so any idea about doing in php function itself.
I have 2 date ranges
[contract_start_date] => 2011-10-20 [contract_end_date] => 2011-10-29
and I want to verify if the dates below are in range of the date range above
2011-05-05 and 2011-10-10
the dates given must not in any way exceed the range of the contract
Is there a function for this in PHP ?
See:: http://php.net/manual/en/datetime.diff.php
$datetime1 = new DateTime('2011-10-20');
$datetime2 = new DateTime('2011-10-29');
//PHP 5.3.0
$interval = $datetime1->diff($datetime2);
echo $interval->format('%R%a days');
//PHP 5.2.2
var_dump($datetime1 < $datetime2);
$datetime3 = new DateTime('2011-05-05');
$datetime4 = new DateTime('2011-10-10');
if ($datetime3 > $datetime1 && $datetime2 > $datetime1 && $datetime3 < $datetime2 && $datetime2 < $datetime2) {
//valid range
}//end if
$start = strtorime($contract_start_date);
$end = strtotime($contract_end_date);
$required_start = strtotime("2011-05-05");
$required_end = strtotime("2011-10-10");
if ($end > $required_end or $end < $required_start)
{
//out of range
}
if ($start < $required_start or $start > $required_end)
{
//out of range
}
This should give you exactly what you're looking for:
define(CONTRACT_START, "2011-10-20");
define(CONTRACT_END, "2011-10-29");
function checkDateRange($dateArray)
{
foreach($dateArray as $dateStr)
{
$curDate = strtotime($dateStr);
if($curDate < strtotime(CONTRACT_START) || $curDate > strtotime(CONTRACT_END))
{
return false;
}
}
return true;
}
$dates = array( 0 => "2011-10-02", 1 => "2011-10-25");
if(checkDateRange($dates))
{
echo "Dates are within range";
}
else
{
echo "Dates are NOT within range";
}
Find below code to get date difference in days, month and year:
<?php
function datediff($date1,$date2,$format='d'){
$difference = abs(strtotime($date2) - strtotime($date1));
switch (strtolower($format)){
case 'd':
$days = round((($difference/60)/60)/24,0);
break;
case 'm':
$days = round(((($difference/60)/60)/24)/30,0);
break;
case 'y':
$days = round(((($difference/60)/60)/24)/365,0);
break;
}
return $days;
}
//Example
echo datediff('2011-06-1','2010-8-30','D') . ' Days<br />';
echo datediff('2011-06-1','2010-8-30','m') . ' Months<br />';
echo datediff('2011-06-1','2010-8-30','y') . ' Years<br />';
?>