【问题标题】:Convert jQuery date to php date or mysql date to be inserted correctly in database将 jQuery 日期转换为 php 日期或 mysql 日期以正确插入数据库
【发布时间】:2012-08-30 17:47:51
【问题描述】:

我使用带有以下代码的 jQuery 日期选择器

$(".item").datepicker({
  showWeek: true,
  firstDay: 1,
  minDate: -30,
  dateFormat: 'mm-dd-yy'
});

该日期选择器的值将通过 ajax 发送到 php 函数,该函数在 mysql 表中插入数据。

mysql 数据库中的date 列类型为Datetime

每次从 datepicker 输入值中读取值时,数据库中的date 列为空显示00-00-0000 00:00:00

我是 php 的新手,也许我在某个地方犯了错误。

php 代码段

mysqli_query($connect, "Insert into tab(date) values ('".$myData."')");

如何为 mysql 格式化 javascript 日期?

【问题讨论】:

  • 你真的需要时间部分吗?
  • 我很确定这个问题可能已经被问过几千次了
  • 时间不重要,按日期时间列类型添加
  • 在我的情况下使用 yy-mm-dd

标签: php javascript jquery mysql


【解决方案1】:

您能否首先验证日期选择器是否向服务器发布了正确的值?

尝试在某处提醒值。

如果您从 javascript 获得正确的输入,则脚本的 php 部分可以这样完成:

if (isset$_GET['date']){$date=$_GET['date'];}
$date=date("Y-m-d h:i:s",strtotime($date));

回显以确认您正确,最后将该 $date 插入表中。

【讨论】:

    【解决方案2】:

    mysql中的日期格式是YYYY-MM-DD所以你可以使用strtotime:

    $myDataSQL = date("Y-m-d", strtotime($myData));
    mysqli_query($connect, "Insert into tab(date) values ('".$myDataSQL."')");
    

    顺便说一句,我建议使用准备好的语句来避免 sql 注入问题,尽管在这种特定情况下这并不重要。我总是使用准备好的语句,所以我不必考虑它。

    编辑:似乎strtotime needs / separators 可以工作。

    如果您使用的是 PHP 5.3+,则可以使用 DateTime 类:

    $date = DateTime::createFromFormat('m-d-y', $myData);
    $myDataSQL = $date->format('Y-m-d');
    mysqli_query($connect, "Insert into tab(date) values ('".$myDataSQL."')");
    

    【讨论】:

    • @Snake Eyes 似乎 strtotime 不喜欢您的输入格式,请参阅我的编辑。
    • createFromFormat 需要 2 个参数
    • 是的,但是发生了致命错误:在非对象上调用成员函数 format() ...
    • @Snake Eyes 您是否将日期添加为第二个变量(我已经编辑了答案)?
    • 是的,问题是格式不是 createfromformat。我有 php 5.4.4
    【解决方案3】:

    查询根据mysqldocumentation:

    作为 'YYYY-MM-DD' 或 'YY-MM-DD' 格式的字符串。允许使用“宽松”语法:任何标点字符都可以用作日期部分之间的分隔符。例如,“2012-12-31”、“2012/12/31”、“2012^12^31”和“2012@12@31”等价。

    因此您可以更改 datepicker 获取日期的格式。

    $( ".item" ).datepicker({ dateFormat: "yy-mm-dd" });
    

    将其放入您的更新中应该可以解决问题,您甚至不需要额外的服务器操作来进行解析。只需确保它能够安全地到达服务器即可。

    【讨论】:

      【解决方案4】:

      对 jeroen 的答案的不同看法,同样合适

      $myDataSQL = date("c", strtotime($myData));
      mysqli_query($connect, "Insert into tab(date) values ('".$myDataSQL."')");
      

      我发现在任何地方都使用 ISO 8601 日期更容易处理时区,因为它们是可见的。加上它插入到mysql中。

      过去我也遇到过 jQuery datapicker 的问题,需要在初始化时指定更好的格式。

      不妨试试

      $(".item").datepicker({
          showWeek: true,
          firstDay: 1,
          minDate: -30,
          dateFormat: "yy/mm/dd"
      });
      

      【讨论】:

        【解决方案5】:

        我使用转换器(这里的源代码:https://github.com/lingtalfi/DatePickerHelper/blob/master/DatePickerHelper.php

        用法:

        <?php
            echo DatePickerHelper::convertFromDatePickerToPhpDate("dd/mm/yy"); // prints d/m/Y
            echo DatePickerHelper::convertFromPhpDateToDatePicker("Y-m-d"); // prints yy-mm-dd
            $birthdayDate = "09/12/1944"; // your input from the web
            echo DatePickerHelper::convertFromNumericInputToMysqlDate($birthdayDate, "d/m/Y"); // 1944-12-09
        

        -

        class DatePickerHelper
        {
        
        
            private static $map = [
                "yy" => "<1>",
                "y" => "<2>",
                "MM" => "<3>",
                "M" => "<4>",
                "mm" => "<5>",
                "m" => "<6>",
                "DD" => "<7>",
                "D" => "<8>",
                "oo" => "<9>",
                "o" => "<10>",
                "dd" => "<11>",
                "d" => "<12>",
            ];
        
            private static $map2 = [
                "<1>" => 'Y',
                "<2>" => 'y',
                "<3>" => 'F',
                "<4>" => 'M',
                "<5>" => 'm',
                "<6>" => 'n',
                "<7>" => 'l',
                "<8>" => 'D',
                "<9>" => 'z', // note: php doesn't have "day of the year with three digits", but this is the closest
                "<10>" => 'z',
                "<11>" => 'd',
                "<12>" => 'j',
            ];
        
        
            private static $mapRegex = [
                'Y' => '<1>',
                'y' => '<2>',
                'm' => '<3>',
                'n' => '<4>',
                'd' => '<5>',
                'j' => '<6>',
            ];
        
            private static $mapRegex2 = [
                '<1>' => '(?P<year4>[0-9]{4})',
                '<2>' => '(?P<year2>[0-9]{2})',
                '<3>' => '(?P<month_leading>[0-9]{2})',
                '<4>' => '(?P<month_no_leading>[0-9]{1,2})',
                '<5>' => '(?P<day_leading>[0-9]{2})',
                '<6>' => '(?P<day_no_leading>[0-9]{1,2})',
            ];
        
        
            public static function convertFromDatePickerToPhpDate(string $datePickerFormat): string
            {
                $map = self::$map;
                $map2 = self::$map2;
                $first = str_replace(array_keys($map), array_values($map), $datePickerFormat);
                return str_replace(array_keys($map2), array_values($map2), $first);
            }
        
            public static function convertFromPhpDateToDatePicker(string $phpDate): string
            {
                $map2 = array_flip(self::$map2);
                $map = array_flip(self::$map);
                $first = str_replace(array_keys($map2), array_values($map2), $phpDate);
                return str_replace(array_keys($map), array_values($map), $first);
            }
        
        
            /**
             * @param string $input , the string to convert, the format of this string should match the given phpFormat
             *                  Plus, it must contain exactly:
             *                          - one day component
             *                          - one month component
             *                          - one year component
             *
             * @param string $phpFormat , all components of the phpFormat  have to be one of those:
             *          - Y: year, four digits
             *          - y: year, two digits
             *          - m: numeric month, with leading zeros
             *          - n: numeric month, without leading zeros
             *          - d: numeric day of the month, with leading zeros
             *          - j: numeric day of the month, without leading zeros
             */
            public static function convertFromNumericInputToMysqlDate(string $input, string $phpFormat)
            {
                $map = self::$mapRegex;
                $map2 = self::$mapRegex2;
                $first = str_replace(array_keys($map), array_values($map), $phpFormat);
                $pattern = str_replace(array_keys($map2), array_values($map2), $first);
        
                if (preg_match('!' . $pattern . '!', $input, $match)) {
                    $day = $match['day_leading'] ?? $match['day_no_leading'] ?? null;
                    if (null !== $day) {
                        $day = (int)$day;
                        $month = $match['month_leading'] ?? $match['month_no_leading'] ?? null;
                        if (null !== $month) {
                            if (
                                array_key_exists("year4", $match) ||
                                array_key_exists("year2", $match)
                            ) {
                                // a component of each type is there, we will be able to return a result
                                if (array_key_exists("year4", $match)) {
                                    $year = (int)$match['year4'];
                                } else {
                                    // assumed it's 20, but we don't know really, that sucks.
                                    // That's why you should use year4 instead...
                                    $year = "20" . $match['year2'];
                                    $year = (int)$year;
                                }
        
                                return $year . "-" . sprintf('%02s', $month) . "-" . sprintf("%02s", $day);
                            }
                        }
                    }
                }
                return false;
            }
        
        }
        

        【讨论】:

          【解决方案6】:

          由于在 JavaScript 中日期值是使用 let date = new Date("2017-01-26"); 创建的,因此在 PHP 脚本中格式化日期时必须使用相同的格式。

          只需将您的php日期转换为以下格式date('Y-m-d', $date)

          这将为您提供正确的 javascript &lt;input type="date"&gt; 字段格式。

          【讨论】:

            猜你喜欢
            • 2017-07-08
            • 1970-01-01
            • 2017-10-02
            • 1970-01-01
            • 1970-01-01
            • 2016-04-11
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多