How to compare digits with date PHP - php

Is there a way to convert values to date? I have 3 dropdown lists: day, month and year. If the selected date < today, then the consumers won't be able to click on the buy button til the day i selected in de dropdown.
The problem is, that the date I selected, is a value and not a date. Is there a way to compare my value with the date of today? The code below is the backend of my website, the if statement has to stay on the frontend
$releasedatumdag= get_post_meta( $domeinnaam_extensies->ID, 'releasedatumdag', true );
$releasedatummaand= get_post_meta( $domeinnaam_extensies->ID, 'releasedatummaand', true );
$releasedatumjaar= get_post_meta( $domeinnaam_extensies->ID, 'releasedatumjaar', true );
<tr>
<th>Releasedatum:</th>
<td>
<select name="domeinnaam_extensies_releasedatumdag">
<?php
for($idag = 1; $idag <= 31; $idag++){
echo '<option value="'.$idag.'">'.$idag.'</option>';
}
?>
</select>
<select name="domeinnaam_extensies_releasedatummaand">
<?php
for($imaand = 1; $imaand <= 12; $imaand++){
echo '<option value="'.$imaand.'">'.$imaand.'</option>';
}
?>
</select>
<select name="domeinnaam_extensies_releasedatumjaar">
<?php
for($ijaar = 2000; $ijaar < date("Y")+10; $ijaar++){
echo '<option value="'.$ijaar.'">'.$ijaar.'</option>';
}
?>
</select>
</td>
</tr>

You can use DateTime() to create your date. You then can compare it to another DateTime object representing today since DateTime objects are comparable:
$my_date = DateTime::createFromFormat('d/m/Y', '31/12/2014');
$now = new DateTime();
if ($my_date < $now) {
// do something
}

You have a day, month, and a year so just create a DateTime object and you can get the timestamp for it and compare it to today.
http://www.php.net/manual/en/datetime.construct.php
http://php.net/manual/en/function.checkdate.php
Can string the digits into any format that you want
$dateString = $releasedatumdag . '/' . $releasedatummaand . '/' . $releasedatumjaar;
//Make sure that they didn't try to create Feb. 31
if(checkdate($dateString)) {
$submittedTime = new DateTime($dateString);
$today = new DateTime();
//DO YOUR COMPARISON HERE
}

Related

How to add 3 drop down in single variable in php?

Two days ago I had an interview as a php developer and they gave me a task to perform.
I completed 90% of the task, but I failed while trying to add date, month and year together.
I have 3 dropdowns for date, month and year:
Date Of Birth : <br />
Date : <select name="date">
<?php $i=1; for($i=1; $i<=31; $i++){ ?> <option> <?php echo $i?> </option> <?php } ?>
</select>
Month : <select name="month">
<option value="January">January</option>
<option>Febuary</option>
<option>March</option>
<option>April</option>
<option>May</option>
<option>June</option>
<option>July</option>
<option>August</option>
<option>September</option>
<option>October</option>
<option>November</option>
<option>December</option>
</select>
Year :
<?php
$currently_selected = date('Y');
$earliest_year = 1950;
$latest_year = date('Y');
print '<select name="year">';
foreach ( range( $latest_year, $earliest_year ) as $i ) {
print '<option value="'.$i.'"'.($i === $currently_selected ? ' selected="selected"' : '').'>'.$i.'</option>';
}
print '</select>';
?>
I have only one column in the database for the date of birth.
I want to add the date, month and year together, which should result in the following: date/month/year.
How could I accomplish this?
if(isset($_POST['submit'])){
$name = trim($_POST['username']);
$date = $_POST['date'];
$month = $_POST['month'];
$year = $_POST['year'];
if($name == ''){
$error = "Add Name";
}
$DateOfBirth = $date.'/'$month;
if(!$error){
echo $DateOfBirth;
}
}
Assuming your date of birth field is a MySQL DATE field, you need to make sure that you are creating a date in the correct format i.e. YYYY-MM-DD. You can do that by using strtotime to convert your input data into a timestamp, and then date to convert that into the appropriate format:
$DateOfBirth = date('Y-m-d', strtotime("$date $month $year"));
For example:
$year = 2015;
$month = 'August';
$date = 5;
$DateOfBirth = date('Y-m-d', strtotime("$date $month $year"));
echo $DateOfBirth;
Output:
2015-08-05
Demo on 3v4l.org
Note
If you really want the result to be in dd/mm/yyyy format, just change the first input to date to 'd/m/Y'.
The reason is your are not concatenating the variables in php. Check below code. You are almost there but with small coding mistake.
What you are trying to do is concatenate a variable with a string. So you have to concatenate variable with a '.' and then add your string. In here / works as the string. When adding a string it should be with in quotations '/' . And the final output will be something like this. $variable . '/'. Now concatenate another variable. Then it would be like this. $variable01 . '/' . $variable02.
$DateOfBirth = $date.'/'.$month.'/'.$date ;
Output
12/02/2020
Check the added example with respect to your requirement
example

Calculate age in php

Hey guys I am working on my colleague project and he used below code to store age from database and shows age in view
He select date and month from select tag.
view BOD select tag image
<?php $today = date("Y");
$year = $today - 18;?>
<select class="form-control" id="date" name="day" >
<option label=01 value=01>01</option>
<option label=02 value=02>02</option>
<option>.......</option>
<option label=30 value=30>30</option>
<option label=31 value=31>31</option>
</select>
<select class="form-control" id="month" name="month" >
January
<option label=January value=01>January</option>
February
<option label=February value=02>February</option>
<option>.......</option>
November
<option label=November value=11>November</option>
December
<option label=December value=12>December</option>
</select>
<select class="form-control" id="year" name="year" >
<?php for($i = 0; $i <= 75; $i++):?>
<option value=<?=$year?>><?=$year?></option>
<?php echo $year = $year -1 ;?>
<?php endfor;?>
</select>
result image
controller
public function user_register()
{
$data = array(
'u_day'=>$this->input->post('day'),
'month'=>$this->input->post('month'),
'year'=>$this->input->post('year'),
'age'=>$this->getAge($this->input->post('year')),
);
$id = $this->admin_model->insertData('users',$data);
$sess = array(
'userid'=>$id,
'fname'=>$this->input->post('first_name'),
'mname'=>$this->input->post('middle_name'),
'lname'=>$this->input->post('last_name'),
'gender'=>$this->input->post('gender'),
'reg'=>'1',
);
$this->session->set_userdata($sess);
redirect($this->config->item('base_url').'profile/basic_details');
}
public function getAge($then) {
$then_ts = strtotime($then);
$then_year = date('Y', $then_ts);
$age = date('Y') - $then_year;
if(strtotime('+' . $age . ' years', $then_ts) > time()) $age--;
//print_r($age);exit;
return $age;
}
It works perfectly when I select any other date.
but when I select (01/01/2000) date it store age in database as -1
Generate the birth date by concatenating the strings.
$date1 = date_create("2013-03-15"); // generate this by "$date-$month-$year"; // your case
$date2 = date("Y-m-d"); // get today's date
$diff = date_diff($date1,$date2); //here you get the difference
You can apply mathematical operations to get exact exact years and months.
**Php Version >= 5.3**
# **get date and change date formate**
$from = new DateTime('1970-02-01');
$to = new DateTime('today');
echo $from->diff($to)->y;
echo date_diff(date_create('1970-02-01'), date_create('today'))->y;
**Mysql Version >= 5.0**
SELECT TIMESTAMPDIFF(YEAR, '1970-02-01', CURDATE()) AS age
I can not see any code in the question that attempts to calculate the age of a user as suggested by the title of the question - consequently can not suggest how to edit the code appropriately. However, as I mentioned in my comment and has been used elsewhere in answers by #Danyal & #Anil, it would be easier and more reliable to use the DateTime class with it's associated methods.
The code below is just a quick rewrite of the question to make it viable and enable the demo to work. The code that processes the user selection is within the if code block below and should be well commented.
$today = date( 'Y' );
$year = $today - 18;
$maxyears = 120;
$html=array();
$html[]='<form method="post">';
/* days */
$html[]='<select class="form-control" name="day">';
for( $i=1; $i <= 31; $i++ )$html[]=sprintf('<option value=%d>%d',$i,$i);
$html[]='</select>';
/* months */
$html[]='<select class="form-control" name="month">';
for( $i=1; $i <= 12; $i++ )$html[]=sprintf('<option value=%d>%s', $i, date('F',mktime( 0, 0, 0, $i ) ) );
$html[]='</select>';
/* years */
$html[]='<select class="form-control" name="year">';
for( $i=$year; $i >= ( $today - $maxyears); $i-- )$html[]=sprintf('<option value=%d>%d',$i,$i);
$html[]='</select>';
$html[]='<input type="submit" />';
$html[]='</form>';
/* output menus */
echo implode( PHP_EOL, $html );
/***** Process Form submission and calculate Age *****/
if( $_SERVER['REQUEST_METHOD']=='POST' && isset( $_POST['day'], $_POST['month'], $_POST['year'] ) ){
/* Establish rules for filtering POSTED data */
$args=array(
'day' => FILTER_SANITIZE_NUMBER_INT,
'month' => FILTER_SANITIZE_NUMBER_INT,
'year' => FILTER_SANITIZE_NUMBER_INT
);
/* Filter POST data */
$_POST=filter_input_array( INPUT_POST, $args );
/* Extract data to variables */
extract( $_POST );
/* create a new date using supplied POST data - using `mktime` to generate a valid timestamp */
$date = date( 'Y-m-d', mktime( 0, 0, 0, $month, $day, $year ) );
/* create DateTime objects and calculate age ( date difference ) */
$now = new DateTime();
$dob = new DateTime( $date );
/* use the `diff` method to find the difference between two dates */
$diff = $now->diff( $dob );
/*
show the age
use the `$diff->format('%y')` method or the shorthand method `$diff->y`
*/
printf('Age: %d', $diff->y ); #same as $diff->format('%y');
Looking at the getAge function produced very odd results - so I tweaked it and arrived at the following - seems to more or less do what is needed.
function getAge( $date ) {
$now = date( 'Y' );
$diff = $now - $date;
if( strtotime( '+' . $diff . ' years', strtotime( $date ) ) < time() ) $diff--;
return $diff;
}
echo getAge( 2017 ); // -> 1
echo getAge( 2000 ); // -> 18

How can I echo out the selected date

does anyone know how I would echo out the selected date as text with the date month and year separated outside of the form? I tried echoing out $date $month and $year outside of the form however this doesn't give me the correct date thankyou for the help
<?
$date = array('16-01-14','16-01-28','16-02-14','16-02-28','16-03-14','16-03-28','16-04-14','16-04-28',
'16-05-14','16-05-28','16-06-14','16-06-28','16-07-14','16-07-28','16-08-14','16-08-28','16-09-14','16-09-28','16-10-14','16-10-28',
'16-11-14','16-11-28','16-12-14','16-12-28');
$currentdate = date('y-m-d');
echo $currentdate;
?>
<form>
<select style="width:200px;">
<?php
foreach ($date as $i => $d) {
if ($currentdate >= $d && ($i == count($date)-1 || $currentdate < $date[$i+1])) {
$selected = "selected";
} else {
$selected = "";
}
list($year, $month, $day) = explode('-', $d);
echo "<option $selected>" . date("m/d/Y", strtotime($d)) . "</option>";
echo 'the current billing period is';
}
?>
</select>
</form>
Inside of your loop add a $selected_int variable like so:
foreach ($date as $i => $d) {
if ($currentdate >= $d && ($i == count($date)-1 || $currentdate < $date[$i+1])) {
$selected = "selected";
$selected_int = $i;
} else {
$selected = "";
}
list($year, $month, $day) = explode('-', $d);
echo "<option $selected>" . date("m/d/Y", strtotime($d)) . "</option>";
echo 'the current billing period is';
}
Then, you can reference it like:
echo date('Y-m-d', strtotime($date[$selected_int]));
Addition
I know you've already accepted the answer, but I also wanted to make a suggestion now that I see what you are using the $date for. Since you know the start date, and it is in 14-day periods, it would be easy to write that as part of the loop.
$start_date = date('Y-m-d', strtotime(date('Y').'-01-01'); //First day of the year, for the sake of argument.
$interval = 14;
for ($i = 0; date('Y') == date('Y', strtotime($start_date.' +'.($i * $interval).' days')); $i++) {//While this year is equal to the start date's year with the added interval [If I knew what your logic here was I could offer a better suggestion]
if ($currentdate >= date("Y-m-d", strtotime($start_date.' +'.($i * $interval).' days')) && (date('Y') < date("Y", strtotime($start_date.' +'.(($i + 1) * $interval).' days')) || $currentdate < date("m/d/Y", strtotime($start_date.' +'.(($i + 1) * $interval).' days')))) {
$selected = "selected";
$selected_int = $i;
} else {
$selected = "";
}
echo "<option $selected>" . date("m/d/Y", strtotime($start_date.' +'.($i * $interval).' days')) . "</option>";
}
Basically, this takes the start date, shows it as the first date option, then adds 14 days to it with each pass through. Your if/else statement should still be the same. It checks to see if you are on the last interval of the year, or if the current date is less than the next interval, and also that the current date is greater than the current interval.
After your loop, you can get the date by:
echo date("m/d/Y", strtotime($start_date.' +'.($selected_int * $interval).' days'));
I know it seems like a lot, but it would save you from having to make a date array to begin with.
Use strtotime instead list.
....
// list($year, $month, $day) = explode('-', $d);
echo "<option $selected>" . date("m/d/Y", strtotime($d)) . "</option>";
....
EDIT: Additional information - your code requires a lot modification and likely some structure changes but assuming this is for testing a method and "how to do" instead a final product.
You need to submit the selected date, catch it in the script and use the selected date to do what you need - i.e. retrieve data from database - and this should give you some idea.
<?php
// You need to create these dates by using another method. You cannot hard code these. You can create it with date functions easily.
$date = array('16-01-14','16-01-28','16-02-14','16-02-28','16-03-14','16-03-28','16-04-14','16-04-28','16-05-14','16-05-28','16-06-14','16-06-28','16-07-14','16-07-28','16-08-14','16-08-28','16-09-14','16-09-28','16-10-14','16-10-28','16-11-14','16-11-28','16-12-14','16-12-28');
// Checking if we have a posted form, with the button name user clicked
if (isset($_POST["btnSubmit"])) {
// This is your selected day - use it where you need:
$selectedDate = $_POST["selectedDate"];
// This is where your model start singing and gets necessary info for this date - just printing here as sample
print $selectedDate;
// I need dropDownDate to compare in the SELECT to preselect the appropriate date
$dropDownDate = strtotime($selectedDate);
} else {
// First time visit, preselect the nearest date by using current date
$dropDownDate = time();
}
?>
<form method="post">
<select name="selectedDate" style="width:200px;">
<?php
foreach ($date as $i => $d) {
if ($dropDownDate >= strtotime($d) &&
(!isset($date[$i+1]) || ($dropDownDate < strtotime($date[$i+1])))
) {
$selected = 'selected="selected"';
} else {
$selected = "";
}
list($year, $month, $day) = explode('-', $d);
echo "<option $selected>" . date("m/d/Y", strtotime($d)) . "</option>";
}
?>
</select>
<input type="submit" name="btnSubmit" value="Submit">
</form>
Note that I added a "submit" type input (to submit the form) and changed form method to "post", finally named SELECT as "selectedDate". I also changed your date comparison code line in the loop.
Hope this helps.

Select dropdown from date range

Is there a simple if statement to default select the correct date from the dropdown? so for example if the date is 02/11/16 then it will default select
01/28/16
Basically what I'm asking for is an if statement that default selects the drop-down that the date is within
<?php
date_default_timezone_set('US/Eastern');
$currenttime = date('d:m:y:h:i:s A');
list($day,$month,$year) = split(':',$currenttime);
$currentdate = "$month/$day/$year";
?>
<form>
<select>
<option>01/14/16</option>
<option>01/28/16</option>
<option>02/14/16</option>
///the list goes on for ages so i saved time and cropped out the rest of the dates.
</select>
</form>
Put all the dates in an array, and loop through them. Then you can test them and decide whether the current date is in the billing period.
$dates = array('16-01-14',
'16-01-28',
'16-02-14',
...);
$currentdate = date('y-m-d');
?>
<form>
<select>
<?php
foreach ($date as $i => $d) {
if ($currentdate >= $d && ($i == count($dates)-1 || $currentdate < $dates[$i+1])) {
$selected = "selected";
} else {
$selected = "";
}
list($year, $month, $day) = explode('-', $d);
echo "<option $selected>$month/$day/$year</option>";
}
?>
</select>
</form>
I changed the format of $currentdate to y-m-d so that they can be compared as strings to see if the date is in a range.
As it loops through the list of dates, it tests whether the current date is between that date and the next date in the array (or it's the last date in the array). If it is, it adds the selected attribute to the <option>.

strtotime question

This should be a simple fix;
I currently have a calendar for selecting a range of date:
http://protekco.com/index.php/en/reservations/1718-carvelle-drive-westpalm-beach.html
When the dates are selected in the calendar, it populates 2 input fields for Check in and Check out dates. The problem is, the calendar initially was set 1 day late, so Thursday Sept 22 actually showed as a Thursday Sept 21. I was able to just echo a +1 on the day count, but the input boxes still show the erroneous date. Essentially, I'm trying to add the same +1, but because the date is returned as yyyy/mm/dd, +1 doesn't do much.
Here is the code:
$listsFrom = $this->lists['from'];
$selectedFrom = $listsFrom ? strtotime($listsFrom) : 0;
$listsTo = $this->lists['to'];
$selectedTo = $listsTo ? strtotime($listsTo) : $selectedFrom;
if ($selectedTo) {
ADocument::addDomreadyEvent('Calendars.checkOut = ' . $selectedTo . ';');
}
if ($selectedFrom) {
ADocument::addDomreadyEvent('Calendars.checkIn = ' . $selectedFrom . ';');
}
$listOperation = $this->lists['operation'];
ADocument::addDomreadyEvent('Calendars.operation = ' . $listOperation . ';');
Any ideas?
Thank you!
Edit:
<td class="<?php echo implode(' ', $class); ?>" <?php if ($canReserveBox) { ?> id="day<?php echo $firstDay->Uts+84600000; ?>" onclick="Calendars.setCheckDate('day<?php echo $firstDay->Uts+84600000; ?>','<?php echo AHtml::getDateFormat($firstDay->date, ADATE_FORMAT_MYSQL_DATE, 0); ?>','<?php echo AHtml::getDateFormat($firstDay->date, ADATE_FORMAT_NORMAL); ?>')"<?php } ?> >
<span class="date" >
<?php echo AHtml::getDateFormat($firstDay->date, ADATE_FORMAT_NICE_SHORT)+1;
?>
</span>
This is what actually calls the changes. The + 84600000 is my addition, it doesn't seem to do much tho.
If the date is in yyyy/mm/dd format, first use strtotime() to convert it to a timestamp, and then you can use it again to add one day.
$date = '2011/06/01';
$ts = strtotime('+24 hours', strtotime($date));
$date = date('Y/m/d', $ts);
That is just one possible solution.

Categories