简体   繁体   中英

Getting first day of month in PHP 5.2.6?

I have following scenario: Datepicker for user to choose Year,Month, and use it to display records for the selected month. The selected value is passed to details_subcontractor.php, using Ajax. Datepicker has been modified from accepted answer in jQuery UI DatePicker to show month year only . Sample code as below:

/**
 *  Datepicker in datepicker.php
 *
 */

$("#year_month").datepicker({"dateFormat":"yy-mm-dd",
    changeMonth: true,
    changeYear: true,
    dateFormat: 'yy-mm',
    showButtonPanel: true,
    onClose: function(dateText, inst) { 
        var month = $("#ui-datepicker-div .ui-datepicker-month :selected").val();
        var year = $("#ui-datepicker-div .ui-datepicker-year :selected").val();
        $(this).datepicker('setDate', new Date(year, month, 1));
    }
});

/**
 *  Ajax call
 *
 */

var year_month = $("#year_month").val();
$.ajax({
    url:"details_subcontractor.php",
    data:{
        year_month:year_month
    },
    success:function(data){
        $("#content_report").html(data);
    }
});


/**
 *  details_subcontractor.php
 *
 */

//$_GET['year_month']; //2012-12
$start = date('Y-m-d', strtotime($_GET['year_month']));                     //2012-12-18
$start = date('Y-m-d', strtotime('first day of ' . $_GET['year_month']));   //1970-01-01
$start = date('Y-m-d', strtotime($_GET['year_month'] . ' first day'));      //2012-12-19
$end   = date('Y-m-d', strtotime('last day of ' . $_GET['year_month']));    //1970-01-01
$end   = date('Y-m-d', strtotime($_GET['year_month'] . ' last day'));       //2012-12-17

However, as the inline comment shows, I can't get first day and last day of the Month. I'm aware that 'of' is introduced at PHP 5.3, where the 2 lines that contain 'of' are failed, but I don't understand the output of other three. I ended up with appending '-01' and '-31' to indicate first and last day of month. Does anyone have a better solution, that works in PHP 5.2.6?

You can safely assume that the first day of every month is 1 . Use

date('Y-m-t', strtotime($_GET['year_month']));

for the last day of the month.

// The first day is always 01, so you can hardcode it
$start = date('Y-m-01', strtotime($_GET['year_month']));

// last day you can get by `t` format parameter, which contains total days count for given month.
$end = date('Y-m-t', strtotime($_GET['year_month']));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM