how to get the first and last days of a given month

how to get the first and last days of a given month

Asked on December 27, 2018 in PHP.
Add Comment


  • 3 Answer(s)

    The strtotime() and date() functions can be used for get the first and last days of the given month.

    <?php
     
    $query_date = '2010-02-04';
     
    // First day of the month.
    echo date('Y-m-01', strtotime($query_date));
     
    // Last day of the month.
    echo date('Y-m-t', strtotime($query_date));
    
    Answered on December 27, 2018.
    Add Comment

    This code for php 5.3+ users,

    $query_date = '2010-02-04';
    $date = new DateTime($query_date);
    //First day of month
    $date->modify('first day of this month');
    $firstday= $date->format('Y-m-d');
    //Last day of month
    $date->modify('last day of this month');
    $lastday= $date->format('Y-m-d');
    

    To find the last day of next month, one can use this code.

    $date->modify('last day of 1 month');
    echo $date->format('Y-m-d');
    
    Answered on December 27, 2018.
    Add Comment

    Use this code simply,

    $first = date("Y-m-d", strtotime("first day of this month"));
    $last = date("Y-m-d", strtotime("last day of this month"));
    
    Answered on December 27, 2018.
    Add Comment


  • Your Answer

    By posting your answer, you agree to the privacy policy and terms of service.