Get the Year/Month/Day from a datetime in php?

Php

Php 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>

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAnonView Question on Stackoverflow
Solution 1 - PhpKingCrunchView Answer on Stackoverflow
Solution 2 - PhpetuarduView Answer on Stackoverflow
Solution 3 - PhpKhaled ShehataView Answer on Stackoverflow