doujiabing1228
2012-12-19 13:00 阅读 39

在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?

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享

2条回答 默认 最新

  • 已采纳
    douluoxiao2286 douluoxiao2286 2012-12-19 13:09

    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.

    点赞 评论 复制链接分享
  • dounao4179 dounao4179 2012-12-19 13:12
    // 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']));
    
    点赞 评论 复制链接分享

相关推荐