如何格式化从数据库接收的日期并在jquery函数中使用它

时间:2017-03-06 20:16:58

标签: php jquery datepicker

我在mm-dd-yyyy格式的表格中有一列。我有以下脚本来禁用日期选择器中的某些日期。

 <script>
 jQuery(function($){
//var disabledDays = <?php echo json_encode($dates); ?>;
 var disabledDays = [
 "27-4-2016", "25-12-2017", "26-12-2017",
 "4-3-2017", "5-4-2017", "6-4-2017", "6-4-2016", "7-4-2017", "8-4-2017", "9-4-2017"
];
//replace these with the id's of your datepickers
$("#datepicker").datepicker({
    beforeShowDay: function(date){
    var day = date.getDay();
    var string = jQuery.datepicker.formatDate('d-m-yy', date);
    var isDisabled = ($.inArray(string, disabledDays) != -1);
//day != 0 disables all Sundays
//return [day != 0 && !isDisabled];
return [!isDisabled];

}});
$("#datepicker").on("change",function(){
            var selected = $(this).val();
             $("#date").text(selected);
              $('input[name="date"]').attr('value', selected);
        });
}); 
  </script>

我用它来从mysql数据库中选择日期。

$sql="select display_date from login_ads where display_type='static'";
$res = mysql_query($sql);
while ($static_purchased_dates = mysql_fetch_array($res)){
    $dates[] =  $static_purchased_dates['display_date'];
}
echo json_encode($dates);   

以此格式返回日期:

["03\/04\/2017","03\/04\/2017"]

我的问题是如何从mysql中检索日期,例如脚本中用来禁用日期的格式。

我对PHP非常陌生,感谢提前帮助。

由于

2 个答案:

答案 0 :(得分:0)

您可以使用一些PHP来解决您的问题。 你可以这样做:

$sql="select display_date from login_ads where display_type='static'";
$res = mysql_query($sql);
while ($static_purchased_dates = mysql_fetch_array($res)){
    $date = DateTime::createFromFormat('d/m/Y', $static_purchased_dates['display_date']);
    $dates[] =  $date->format('Y-n-d');
}
echo json_encode($dates);

答案 1 :(得分:0)

您的表格列display_date可能采用格式&#34; mm / dd / yyyy&#34; (不是&#34; mm-dd-yyyy&#34;)所以json_encode将它转换为&#34; mm \ / dd \ / yyyy&#34;。

根据专栏:

var string = jQuery.datepicker.formatDate('d-m-yy', date);

你需要&#34; mm / dd / yyyy&#34;转换为&#34; d-m-yyyy&#34; (几天和几个月没有前导零)。

第一个选项(没有DateTime):

$sql="select display_date from login_ads where display_type='static'";
$res = mysql_query($sql);
while ($static_purchased_dates = mysql_fetch_array($res)){
    $tempD = $static_purchased_dates['display_date'];

    $tempD = substr($tempD,3,2).'-'.substr($tempD,0,2).'-'.substr($tempD,6,6);
    $tempD = str_replace('-0', '-', $tempD);
    if( substr($tempD,0,1) == '0' )
      $tempD = substr($tempD,1);

    $dates[] = $tempD;
}
echo json_encode($dates);

第二个选项(w / DateTime):

$sql="select display_date from login_ads where display_type='static'";
$res = mysql_query($sql);
while ($static_purchased_dates = mysql_fetch_array($res)){
    $tempD = $static_purchased_dates['display_date'];

    $tempDT = DateTime::createFromFormat('m/d/Y', $tempD);
    $dates[] =  $tempDT->format('j-n-Y');
}
echo json_encode($dates);

PHP DateTime格式:http://php.net/manual/en/function.date.php