使用php数组从datePicker

时间:2017-07-05 22:56:23

标签: javascript php jquery datepicker timepicker

我有一个日期选择器输入和一个时间戳输入,我想用来安排一个人进行约会。

当用户点击输入以打开日期选择器菜单时,我想使特定的日期时间变灰。我有一个php函数可以在' Y-m-d中返回这个日期时间数:H:i:s'字符串格式。但我不会'知道如何使用该函数的返回值来为javascript函数提供在datepicker中禁用日期范围所需的功能。

在我的datepicker的onSelect事件中,我希望它根据当天预订的时间段启用/禁用我的时间选择器中的时间选项。但我不知道如何。

  1. Datepicker使用beforeshowDay:禁用预订日期

  2. 用户从datepicker

  3. 中选择日期
  4. Datepicker启用/禁用timepicker中的时间

  5. 我确实了解了如何在timepicker Here中禁用时间范围。代码示例如下:

    $('input.timepicker').timepicker({
        'disableTimeRanges': [
            ['1am', '2am'],
            ['3am', '4:01am']
        ]
    });
    

    但这就是我如何禁用时间戳范围内的时间范围。我不知道如何在datepicker的BeforeShowDay中禁用它们?

    <script type="text/javascript">   
        $(document).ready(function(){
            $( "#datepickerListAppointments" ).datepicker(
            {
                minDate:'0',
                beforeShowDay:
                function(dt)
                {   // need to disable days other than tuesday and wednesday too.
                    return [dt.getDay() === 2 || dt.getDay() === 3, ""];
                },
                onSelect : function(){
                    should disable/enable timepicker times from here?
                }
            });
    
            $('input.timepicker').timepicker({
                timeFormat: 'h:mm p',
                interval: 90,
                minTime: '9',
                maxTime: '10:30am',
                defaultTime: '9',
                startTime: '9:00',
                dynamic: false,
                dropdown: true,
                scrollbar: false                
            });
    
        });
    

    这是提供日期时间的函数,以防有助于了解。

    function get_next_open_appointments($numAppointments, $timeSlotToExclude = "")
    {
        global $db;
        $whereCondition = "WHERE FirstName = :null ";
        if ($timeSlotToExclude != "")
        {
            $whereCondition .= "AND AppointmentTime != '$timeSlotToExclude' ";
        }
    
        $query = "SELECT DISTINCT AppointmentTime FROM appointments
                  $whereCondition
                  ORDER BY AppointmentTime ASC LIMIT $numAppointments";
        $statement = $db->prepare($query);
        $statement->bindValue(':null', "");
        $statement->execute();
        $datesArray = array();
        while ($row = $statement->fetch()) 
        {
            array_push($datesArray, $row['AppointmentTime']);
        }
        $statement->closeCursor();
        return $datesArray;
    }
    

    更新

    Hugo De Carmo指出我正确的方向,我得到适当的禁用/启用日期。但是,我不知道如何使用我在下面的代码中提取的日期时间来禁用/启用时间戳中的时间。

    这是新代码:

    <script type="text/javascript">   
        $(document).ready(function(){
    
            // uses php to get open appointments, and put them in a javascript array
            <?php $datetime_openings = get_next_open_appointments(200);
            $date_openings = array();
            foreach ($datetime_openings as $dt)
            {
                array_push($date_openings, substr($dt,0,10)); // just the date part
            }
    
            $json_date_openings = json_encode($date_openings);
            echo "var arr_Openings = ". $json_date_openings . ";\n";
            ?>
    
            $( "#datepickerOpenAppointments" ).datepicker(
            {
                minDate:'0',
                beforeShowDay:
                function(dt)
                {
                    var string = jQuery.datepicker.formatDate('yy-mm-dd', dt);
                    var bFound = (arr_Openings.indexOf(string) != -1);
                    return [ bFound ]; 
                },
                onSelect : function(){
                   //    Should disable/enable time ranges here?
            });
    
            $('input.timepicker').timepicker({
                timeFormat: 'h:mm p',
                interval: 90,
                minTime: '9',
                maxTime: '10:30am',
                defaultTime: '9',
                startTime: '9:00',
                dynamic: false,
                dropdown: true,
                scrollbar: false                
            });
    
        });
    

3 个答案:

答案 0 :(得分:4)

试试这个,
对不起,我没有使用beforeshowDay
选择日期2017-7-14和2017-7-17并查看

var disabledDateTime = {
  '2017-7-14':[
  	['2:30am','3:00am'],
    ['6:30am','9:00am']
  ],
	'2017-7-17':[
  	['1:00am','3:00am'],
    ['5:30am','7:00am'],
    ['11:30am','2:00pm']
  ]
};

$(function() {
  $('#pickTime').timepicker();
  $('#pickDate').datepicker({
    'format': 'yyyy-m-d',
    'autoclose': true
  }).on('changeDate',function(e){
    var ts = new Date(e.date);
    var m = ts.getMonth()+1;
    var dt = ts.getFullYear() + '-' + m + '-' + ts.getDate();
    var opt = {'disableTimeRanges': []}
    if(typeof(disabledDateTime[dt])!='undefined'){
      $('#pickTime').timepicker('setTime', '');
      opt = {'disableTimeRanges': disabledDateTime[dt]}
    }
    $('#pickTime').timepicker('option',opt);
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<link href="https://jonthornton.github.io/jquery-timepicker/lib/bootstrap-datepicker.css" rel="stylesheet"/>
<script src="https://jonthornton.github.io/jquery-timepicker/lib/bootstrap-datepicker.js"></script>
<link href="https://jonthornton.github.io/jquery-timepicker/jquery.timepicker.css" rel="stylesheet"/>
<script src="https://jonthornton.github.io/jquery-timepicker/jquery.timepicker.js"></script>

<input id="pickDate" type="text" class="date" />
<input id="pickTime" type="text" class="time" />

答案 1 :(得分:3)

有人已经回答了这个问题here

无论如何,以下代码应该让您了解如何解决问题。

// supose your script return a json similar to the following
{
    "data": [
        // ...
        "17-07-11"
    ]
}

$(function() {
  $.getJSON("/path/to/script", function(response){
    $('#datepickerListAppointments').datepicker({
      beforeShowDay: function(dt) {
        var config = [];
        config[1] = 'class';

        if ((dt.getDay() === 2) || (dt.getDay() === 3)) {
          config[0] = false;
          return config;
        }

        var string = jQuery.datepicker.formatDate('yy-mm-dd', dt);
        config[0] = (response.data.indexOf(string) === -1);
        return config;
      }
    });
  });
});

我假设您使用某种API与服务器交换数据,因此使用getJSON,如果您想处理服务器错误,那么我建议您使用{ {3}}与ajax结合。

修改1

您可以使用课程Promise从日期中提取所有内容,以下是摘录:

$openings = array();

$date = DateTime::createFromFormat("y/m/d H:i", "17/07/15 08:30");

if (!isset($openings[$date->format("y-m-d")])) {
    $openings[$date->format("y-m-d")] = array();
}

$openings[$date->format("y-m-d")][] = array(
    "hour" => $date->format("Ha"),
    "minute" => $date->format("i")
);

/* result
array(1) {
  ["17-07-15"]=>
  array(1) {
    [0]=>
    array(2) {
      ["hour"]=>
      string(4) "08am"
      ["minute"]=>
      string(2) "30"
    }
  }
}
*/

然后你可以根据日期禁用timepicker中的时间,你可能需要在你的日期选择器中注册一个回调函数来根据所选日期更新时间戳,或者你必须覆盖时间选择器新设置。

答案 2 :(得分:1)

是的,您可以使用timepicker组件的option方法在disableTimeRanges函数内以dinamically方式更新timepicker onSelect

我想:

  • 您正在使用jQuery UI datepicker(因为您没有使用twitter-bootstrap标记您的问题而bootstrap-datepicker没有minDate选项)
  • 您使用的是get_next_open_appointments的第一个版本,它返回一个日期时间数组(例如['2017-07-25 09:30:00', ...]在代码段中查看fakeDisabledTimes

我正在使用momentjs来简化日期管理。在下面的代码中,我使用了时刻解析函数(moment(String)moment(String, String)),isSameaddformat。请注意,时刻令牌与PHP令牌不同。

这是一份完整的工作样本:

var fakeDisabledTimes = [
  '2017-07-25 09:30:00', '2017-07-26 10:00:00',
  '2017-08-01 09:00:00', '2017-08-02 09:30:00',
  '2017-08-08 10:30:00', '2017-08-09 10:00:00',
  '2017-07-15 09:30:00', '2017-07-16 10:00:00'
];

$(document).ready(function(){
  $( "#datepickerListAppointments" ).datepicker({
    minDate:'0',
    beforeShowDay:
    function(dt){
      // need to disable days other than tuesday and wednesday too.
      return [dt.getDay() === 2 || dt.getDay() === 3, ""];
    },
    onSelect : function(dateText){
      //should disable/enable timepicker times from here!
      // parse selected date into moment object
      var selDate = moment(dateText, 'MM/DD/YYYY');
      // init array of disabled times
      var disabledTimes = [];
      // for each appoinment returned by the server
      for(var i=0; i<fakeDisabledTimes.length; i++){
        // parse appoinment datetime into moment object
        var m = moment(fakeDisabledTimes[i]);
        // check if appointment is in the selected day
        if( selDate.isSame(m, 'day') ){
          // create a 30 minutes range of disabled time
          var entry = [
            m.format('h:mm a'),
            m.clone().add(30, 'm').format('h:mm a')
          ];
          // add the range to disabled times array
          disabledTimes.push(entry);
        }
      }
      // dinamically update disableTimeRanges option
      $('input.timepicker').timepicker('option', 'disableTimeRanges', disabledTimes);
    }
  });

  $('input.timepicker').timepicker({
    timeFormat: 'h:i a',
    interval: 90,
    minTime: '9',
    maxTime: '10:30am',
    defaultTime: '9',
    startTime: '9:00',
    dynamic: false,
    dropdown: true,
    scrollbar: false                
  });

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.11.4/jquery-ui.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-timepicker/1.10.0/jquery.timepicker.js"></script>

<link href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.11.4/jquery-ui.css" rel="stylesheet"/>
<link href="https://cdnjs.cloudflare.com/ajax/libs/jquery-timepicker/1.10.0/jquery.timepicker.css" rel="stylesheet"/>

<input id="datepickerListAppointments" type="text">
<input class="timepicker" type="text">