简体   繁体   English

如何格式化从jQuery datepicker返回的日期输入值,以匹配mysql DATE字段?

[英]How to format the returned date input value from a jQuery datepicker in order to match mysql DATE field?

I have a form with a jQuery datepicker. 我有一个带有jQuery datepicker的表单。 I have set the date format to the European way: dd-mm-yy in order to make it look nice for the user. 我已将日期格式设置为欧洲格式: dd-mm-yy ,以使其对用户看起来不错。 However this date value eventually needs to be formatted back in PHP to yy-mm-dd so that in can be stored in my mysql DATE field . 但是,此日期值最终需要在PHP中重新格式化为yy-mm-dd以便可以将其存储在我的mysql DATE字段中 Here is my code: 这是我的代码:

Jquery: jQuery:

   $("document").ready(function(){

    $(function() {
    $( ".datepicker" ).datepicker({
        monthNames: ['januari', 'februari', 'maart', 'april', 'mei', 'juni',
                     'juli', 'augustus', 'september', 'oktober', 'november', 'december'],
        dayNamesMin: ['Zo', 'Ma', 'Di', 'Wo', 'Do', 'Vr', 'Za'],
        dateFormat:'dd-mm-yy',
        });
});

You have three options (in some vague order of preference): 您有三个选择(按模糊的优先顺序):

  1. Use MySQL's STR_TO_DATE() function to convert the string: 使用MySQL的STR_TO_DATE()函数转换字符串:

     INSERT INTO ... VALUES (STR_TO_DATE(:date, '%d/%m/%Y')) 
  2. Convert the string received from jQuery into a PHP DateTime object: 将从jQuery接收的字符串转换为PHP DateTime对象:

     $dt = DateTime::createFromFormat('d/m/Y', $_POST['date']); 

    and then either: 然后:

    • obtain a suitable formatted string: 获取合适的格式化字符串:

       $date = $dt->format('Ym-d'); 
    • obtain the UNIX timestamp: 获取UNIX时间戳:

       $timestamp = $dt->getTimestamp(); 

      which is then passed directly to MySQL's FROM_UNIXTIME() function: 然后将其直接传递给MySQL的FROM_UNIXTIME()函数:

       INSERT INTO ... VALUES (FROM_UNIXTIME(:timestamp)) 
  3. Manually manipulate the string into a valid literal: 手动将字符串转换为有效的文字:

     $parts = explode('-', $_POST['date']); $date = "$parts[2]-$parts[1]-$parts[0]"; 

Use jQuery UI's altFormat option to have datepicker send the date to the server in an alternate format. 使用jQuery UI的altFormat选项,以使altFormat以另一种格式将日期发送到服务器。 This requires an ID of an alternate field in the form, which can be hidden. 这需要表单中备用字段的ID,该ID可以隐藏。

$( ".datepicker" ).datepicker({
    dateFormat: 'dd-mm-yy',
    altField: '#actualDate',
    altFormat: 'yy-mm-dd'
});

This frees you to show one date format to the user while sending the equivalent date in a date format compatible with MySQL. 这样,您便可以向用户显示一种日期格式,同时以与MySQL兼容的日期格式发送等效日期。

// dd-mm-yy to yy-mm-dd
$date = explode('-',$_POST['date']);
$mysqlDate = $date[2].'-'.$date[1].'-'.$date[0];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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