Get the Year/Month/Day from a datetime in php?
PhpPhp Problem Overview
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.
Php Solutions
Solution 1 - Php
Use DateTime with DateTime::format()
$datetime = new DateTime($dateTimeString);
echo $datetime->format('w');
Solution 2 - Php
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
Solution 3 - Php
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>