2

我使用带有以下代码的 jQuery datepicker

$(".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 日期?

4

6 回答 6

4

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

尝试在某处提醒值。

如果您有来自 javascript 的正确输入,则脚本的 php 部分可以这样完成:

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

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

于 2012-08-30T17:57:27.607 回答
1

mysql 中的日期格式为 YYYY-MM-DD,因此您可以使用strtotime

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

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

编辑:似乎strtotime 需要/分隔符才能工作。

如果您使用的是 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."')");
于 2012-08-30T17:53:28.923 回答
0

查询根据mysql文档

作为 '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" });

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

于 2012-08-30T17:58:35.297 回答
0

对杰罗恩的回答有不同的看法,同样合适

$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"
});
于 2012-08-30T17:59:16.233 回答
0

As in JavaScript date values are created using let date = new Date("2017-01-26");, you have to use the same format when formatting the date in your PHP script.

Just convert yout php date as following format date('Y-m-d', $date).

This will give you the right format for javascript <input type="date"> field.

于 2019-09-10T08:50:41.073 回答
0

我使用转换器(这里的源代码: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;
    }

}
于 2018-06-05T04:43:13.327 回答