I used date('w', timestamp) and date('w', timestamp) to know the day, date('n', timestamp) for months, etc.
Now I'm using datetime and I'd like to know what are the equivalent functions to get a day, a month, etc from a datetime.
PS: I know I could use UNIX_TIMESTAMP() in a SQL query but I prefer avoiding timestamps using in my code.
Use DateTime with DateTime::format()
$datetime = new DateTime($dateTimeString);
echo $datetime->format('w');
Check out the manual: http://www.php.net/manual/en/datetime.format.php
<?php
$date = new DateTime('2000-01-01');
echo $date->format('Y-m-d H:i:s');
?>
Will output: 2000-01-01 00:00:00
Try below code if you want to use php loop to display
<span>
<select name="birth_month">
<?php for( $m=1; $m<=12; ++$m ) {
$month_label = date('F', mktime(0, 0, 0, $m, 1));
?>
<option value="<?php echo $month_label; ?>"><?php echo $month_label; ?></option>
<?php } ?>
</select>
</span>
<span>
<select name="birth_day">
<?php
$start_date = 1;
$end_date = 31;
for( $j=$start_date; $j<=$end_date; $j++ ) {
echo '<option value='.$j.'>'.$j.'</option>';
}
?>
</select>
</span>
<span>
<select name="birth_year">
<?php
$year = date('Y');
$min = $year - 60;
$max = $year;
for( $i=$max; $i>=$min; $i-- ) {
echo '<option value='.$i.'>'.$i.'</option>';
}
?>
</select>
</span>
Related
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
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);
}
?>
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.
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.