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
Related
I have used php timepicker in my project and it is 24 hrs format but in new requirement I need to implement this only 12 hrs format because I have to check time in AM PM format to compare with passed variable value. so what is the process to create in 12 hrs format
<?php
$time = strtotime('10:00');
$end_time = strtotime('20:00');
$end_time = date("h:i a",$end_time);
echo '<select>';
while($time <= $end_time){
$optionvalue = date("H:i",$time);
echo '<option value="'.$optionvalue
.'">'.$optionvalue.'</option>';
$time = strtotime('+15 minutes',$time);
}
echo '</select>';
?>
You need to use date('h:i a') to get meridiem am,pm
$end_time = strtotime('20:00');
$optionvalue = date("h:i a",$end_time);
echo $optionvalue;
Like Demo
/* start and end times converted to DateTime objects */
$start=new DateTime( date( DATE_ATOM, strtotime('10am') ) );
$end=new DateTime( date( DATE_ATOM, strtotime('8pm') ) );
$interval=new DateInterval('PT15M');
/* ensure the initial time is part of the output */
$start->sub( $interval );
$slots=array();
while( $start->add( $interval ) <= $end )$slots[]=$start->format('H:ia');
printf('<select name="times"><option>%s</select>', implode( '<option>', $slots ) );
document.querySelector('select[name="times"]').onchange=(e)=>{
alert( e.target.value )
}
<select name="times">
<option>10:00am
<option>10:15am
<option>10:30am
<option>10:45am
<option>11:00am
<option>11:15am
<option>11:30am
<option>11:45am
<option>12:00pm
<option>12:15pm
<option>12:30pm
<option>12:45pm
<option>13:00pm
<option>13:15pm
<option>13:30pm
<option>13:45pm
<option>14:00pm
<option>14:15pm
<option>14:30pm
<option>14:45pm
<option>15:00pm
<option>15:15pm
<option>15:30pm
<option>15:45pm
<option>16:00pm
<option>16:15pm
<option>16:30pm
<option>16:45pm
<option>17:00pm
<option>17:15pm
<option>17:30pm
<option>17:45pm
<option>18:00pm
<option>18:15pm
<option>18:30pm
<option>18:45pm
<option>19:00pm
<option>19:15pm
<option>19:30pm
<option>19:45pm
<option>20:00pm
</select>
A site contains monthly data in a JSON format. This can be queried like so:
http://www.example.com?startdate=1-1-1985&enddate=31-1-1985
I want to be able to run a script that will obtain the specific data I am looking for, starting from today's month, then work backward until null data is returned. Each month's value needs to add up. So far, this is what I've got:
//Build base URL:
$userid=$_GET['userid'];
$startdate=/*Beginning of today's month*/;
$enddate=/*End of today's month*/;
$url='http://www.example.com?userid='.$userid.'&startdate='.$startdate.'&enddate='.$enddate;
//Set JSON variables:
$get=file_get_contents($url);
$json=json_decode($get);
//Set loop variables:
$value=0;
$month=0;
/*For each month from today backwards{
$number=$json->integer;
if($number!=null){
$value=$value+$number;
$month=$month+1;
}else{
break;
}
}
echo $value;
echo $month;
*/
The part I'm having problems with is the beginning of the fourth part. How do I run a loop that starts with the range of today's month, obtain $number, then repeat with the previous month, until it reaches a month that returns null?
You could use the DateTime object and it's associated methods ( specifically sub in this case ) to count backwards by subtracting 1month at a time. An array stores the months/dates and the url is constructed using the variable counter $i
Initially this has a maximum backwards range of 20years ( which I guessed would be more than enough ) but it's easy to change.
$df='Y-m-d';
$userid=$_GET['userid'];
$timezone=new DateTimeZone('Europe/London');
$interval=new DateInterval('P1M');
$ts=date( $df, strtotime( date('Y-m-1') ) );
$tf=date( $df, strtotime( date('Y-m-1'). ' - 20 years') );
$start=new DateTime( $ts, $timezone );
$end=new DateTime( $tf, $timezone );
$dates=array();
$i=0;
while( $start->sub( $interval ) > $end ){
$dates[]=$start->format( $df );
if( $i > 1 ){
$startdate=$dates[ $i - 1 ];
$enddate=$dates[ $i ];
$url='http://www.example.com?userid='.$userid.'&startdate='.$startdate.'&enddate='.$enddate;
echo $url,'<br />';
/* uncomment when happy with mechanism */
/*
$data=file_get_contents( $url );
if( $data ) ) {
$json=json_decode( $data );
#process.....
break;
}
*/
}
$i++;
}
A snippet of the output
http://www.example.com?userid=bobodaclown&startdate=2017-10-01&enddate=2017-09-01
http://www.example.com?userid=bobodaclown&startdate=2017-09-01&enddate=2017-08-01
http://www.example.com?userid=bobodaclown&startdate=2017-08-01&enddate=2017-07-01
http://www.example.com?userid=bobodaclown&startdate=2017-07-01&enddate=2017-06-01
http://www.example.com?userid=bobodaclown&startdate=2017-06-01&enddate=2017-05-01
http://www.example.com?userid=bobodaclown&startdate=2017-05-01&enddate=2017-04-01
http://www.example.com?userid=bobodaclown&startdate=2017-04-01&enddate=2017-03-01
By using strtotime() and mktime() functions you can while loop until you get Null results. The below code will print 5 urls for 5 months. Change while condition accordingly.
// define $i
$i=0;
$userid = '343';//$_GET['userid']; //dont forget to replace with userid
do{
$timestring = strtotime("now -$i month");
//get Month
$month = date('m',$timestring);
//get Year
$year = date('Y',$timestring);
// First date Month and Year
$startdate = date('d-m-Y', mktime(0, 0, 0, $month, 1, $year));
// Last date Month and Year
$enddate = date('d-m-Y', mktime(0, 0, 0, $month+1, 0,$year));
$url='http://www.example.com?userid='.$userid.'&startdate='.$startdate.'&enddate='.$enddate;
// commenting your code
//Set JSON variables:
//$get=file_get_contents($url);
//$json=json_decode($get);
// $number=$json->integer;
echo $url;
echo "\n";
$i++;
}while ($i!=5); // change while condition according to your requirement. while ($number!=null)
Out Put:
http://www.example.com?userid=343&startdate=01-12-2017&enddate=31-12-2017
http://www.example.com?userid=343&startdate=01-11-2017&enddate=30-11-2017
http://www.example.com?userid=343&startdate=01-10-2017&enddate=31-10-2017
http://www.example.com?userid=343&startdate=01-09-2017&enddate=30-09-2017
http://www.example.com?userid=343&startdate=01-08-2017&enddate=31-08-2017
I got a little question I want to make a loop so I have a dropdown menu with the data. For example: A user has a beginning time of 12:00:00 and an end time of 14:00:00. The loop is supposed to pick out 30 min, so that you have a dropdown menu with 12:00:00, 12:30:00, 13:00:00, 13:30:00 and 14:00:00.
I will get the following data
$starttime = 12:00:00
$endtime = 14:00:00
$talktime = 00:30:00
now I want to make a dropdown menu from it that it loops.
here is my example how I thought it would work.
for ($endtime = $starttime + $talktime){}
But as the code works I want to check the database if the data already exist. I know how to do that part only the loop I don't know.
Already thank you for the help.
<?php
$starttime = new DateTime( '12:00:00' );
$endtime = new DateTime( '14:00:00' );
?>
<select>
<option></option>
<?php
for( $i = $starttime; $i <= $endtime; $i->modify( '+ 30 minutes' ) )
{
?>
<option> <?php echo $i->format( 'H:i' ); ?> </option>
<?php
}
?>
</select>
Each loop adds 30 minutes to the time.
You can try this
<?php
$starttime = new DateTime("12:00:00");
$endtime = new DateTime("14:00:00");
?>
<select name="" id="input" class="form-control" required="required">
<?php
while($starttime <= $endtime)
{
echo "<option value='".$starttime->format('H:i:s')."'>".$starttime->format('H:i:s')."</option>";
$starttime = date_add($starttime, date_interval_create_from_date_string('30 min'));
}
echo " </select>";
Try this
<?php
$starttime = "12:00:00";
$endtime = "14:30:00";
$starttime = strtotime($starttime);
$endtime = strtotime($endtime);
$tNow = $starttime;
while($tNow <= $endtime){
echo date("H:i:s",$tNow)."<br>";
$tNow = strtotime('+30 minutes',$tNow);
}
?>
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
}
I keep having issues on the last day of the month, other than that this code works just fine to display all 12 months starting at the current month. On the last day of the month I get duplicates of some months and others do not show at all. Any help would be appreciated. Thanks.
<select id="month" name="month">
<?php
//lists months
for ($i = 0; $i <= 11; ++$i)
{
$time = strtotime(sprintf('+%d months', $i));
$value = date('m', $time);
$label = date('F', $time);
//if month is set stay on that month
if($month==$value)
{ printf('<option value="%s" selected="selected">%s</option>' , $value, $label);
}
else
{printf('<option value="%s">%s</option>', $value, $label);}
}
?>
//first month shows instead of blank
$("#target option:first")
</select>
You may be running into an issue where from the current day X months later is skipping over a month.
Instead of
strtotime(sprintf('+%d months', $i));
Try using
strtotime(sprintf('first day of +%d month', $i));
<?php
function months($selctedMonth='january'){
$months='<select name="month" size="1">';
for ($i = 12; $i > 0; $i--) {
$time = strtotime(sprintf('-%d months', $i));
$label = date('F', $time);
$selctedM = strtolower($selctedMonth) == strtolower($label) ? 'selected' : '';
$months.="<option value='$label' $selctedM >$label</option>";
}
$months.="</select>";
return $months;
}
echo months();
?>
By default, January will be displayed as selected.
if you write <?php echo months('march'); ?> then march will be selected by default.