Javascript 如何在 PHP 中制作一个不错的“日期选择器”?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4154464/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 11:08:22  来源:igfitidea点击:

How to make a nice "date picker" in PHP?

phpjavascriptdatetimedatepicker

提问by BeeDog

I'm doing some experimenting with MySQL and PHP, and I'm curious about creating a nice "date picker", e.g. picking the date 2010-11-11 (today's date).

我正在对 MySQL 和 PHP 进行一些试验,我很好奇创建一个不错的“日期选择器”,例如选择日期 2010-11-11(今天的日期)。

I want to store valid DATETIME values in my MySQL database, and I want a PHP page to provide rolling lists for year, monthand day(e.g. 2010-11-11) so as to avoid forcing the user to write in dates manually in a form and then do checking.

我想在我的 MySQL 数据库中存储有效的 DATETIME 值,并且我想要一个 PHP 页面来提供(例如 2010-11-11)的滚动列表,以避免强迫用户在日期中手动写入表格,然后做检查。

My question is, let's say the user picks the date 2010-11-31 (which doesn't exist); how can I create the simple rolling lists so as to adjust dynamically? That is, the user FIRST picks the year, then the month, and lastly the day (which is dynamically altered to accommodate the actual number of days in the given month). Hopefully leap years will also be taken care of. After picking them all and the user presses submit, the script will submit a correctly formatted DATETIME value to the database (e.g. YYYY-MM-DD, or YYYYMMDD).

我的问题是,假设用户选择日期 2010-11-31(不存在);如何创建简单的滚动列表以便动态调整?也就是说,用户首先选择年份,然后选择月份,最后选择日期(动态更改以适应给定月份的实际天数)。希望闰年也能得到照顾。全部选中并且用户按下提交后,脚本将向数据库提交格式正确的 DATETIME 值(例如 YYYY-MM-DD 或 YYYYMMDD)。

As far as I have understood, the DATETIME type is strict as standard, meaning the server will keep track of invalid dates, which should be sufficiently easy to error-check. But I want to avoid this by doing what I described above.

据我所知, DATETIME 类型是严格的标准,这意味着服务器将跟踪无效日期,这应该很容易进行错误检查。但我想通过做我上面描述的来避免这种情况。

Would you say my described 'solution' is easy to implement using only PHP (and MySQL)? Or would I need some other stuff (e.g. AJAX/JavaScript, JQuery etc.) to manage this? Any suggestions and pointers are very welcome, especially alternative approaches to the same problem that may be easier to implement. Thanks in advance!

您会说我描述的“解决方案”仅使用 PHP(和 MySQL)就很容易实现吗?或者我需要一些其他的东西(例如 AJAX/JavaScript、JQuery 等)来管理这个?任何建议和指示都非常受欢迎,尤其是可能更容易实施的同一问题的替代方法。提前致谢!

回答by Pekka

There is a lot of JavaScript-based calendar widgets out there already. If you're not looking to do this for learning purposes, no reason to reinvent the wheel.

已经有很多基于 JavaScript 的日历小部件。如果您不是出于学习目的而这样做,那么没有理由重新发明轮子。

Server-side validation is of course still mandatory, but those widgets will make it impossible for the user to select an invalid date under normal circumstances.

服务器端验证当然仍然是强制性的,但是这些小部件会使用户在正常情况下无法选择无效日期。

E.g.

例如

回答by nikc.org

You're trying to solve a client side problem server side here imho, albeit, validation can never be omitted server side.

您正在尝试在这里解决客户端问题服务器端恕我直言,尽管永远不能省略服务器端验证。

But invalid dates, as your example, are really not a problem, as you can use strtotimewhich eats most dates nicely. Of course, in this case, it will evaluate to 1st of December, but a valid date anyway. You can use the output from strtotimewith dateto format it in a database friendly way.

但是无效的日期,例如您的示例,确实不是问题,因为您可以使用strtotimewhich 可以很好地处理大多数日期。当然,在这种情况下,它将评估为 12 月 1 日,但无论如何都是有效日期。您可以使用strtotimewith的输出date以数据库友好的方式对其进行格式化。

To take this slightly further, if you want to make sure the date entered is not only formally valid, you can parse it using strtotime, format it using datein the format it was sent to your script and compare the two strings. If not identical, you'll know something was wrong.

更进一步,如果您想确保输入的日期不仅正式有效,您可以使用 解析它strtotime,使用date发送到脚本的格式对其进行格式化并比较两个字符串。如果不相同,您就会知道有什么问题。

As per your example:

根据您的示例:

$datePosted = '2010-11-31';    
$fromClient = date('Y-m-d', strtotime($datePosted));

// $fromClient == '2010-12-01' 

if (strcmp($datePosted, $fromClient) != 0) {
  // Invalid date posted
} else {
  // All is well on the western front
}

You might also be interested in the DateTimeclass provided with newer versions of PHP.

您可能还对DateTime较新版本的 PHP 提供的类感兴趣。

回答by TRiG

There should be no need for Ajax. Ajax calls back to the server, but the server doesn't know any more about valid dates than the client does, so this can all be done in javascript. If you're already using jQuery, use the jQuery plugin, but don't load the entire jQuery library just for this: that's overkill. There are plenty of lightweight datepickers. All you want to do is reload the available days when someone changes the month/year (remember February: you need to reload on year change too).

应该不需要 Ajax。Ajax 回调服务器,但服务器并不比客户端更了解有效日期,因此这一切都可以在 javascript 中完成。如果您已经在使用 jQuery,请使用 jQuery 插件,但不要为此加载整个 jQuery 库:这太过分了。有很多轻量级的日期选择器。您要做的就是在有人更改月份/年份时重新加载可用天数(请记住二月:您也需要重新加载年份更改)。

We have that done with a method which includes the name of the day of the week alongside the date:

我们使用一种方法完成了这一点,该方法包括日期旁边的星期几的名称:

function OnMonthYearChange(name) {
    var week = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
    var year = document.getElementById(name + '-year');
    var mon  = document.getElementById(name + '-mon');
    var mday = document.getElementById(name + '-mday');
    if ((mon.value  == '') || (year.value == '')) {
        return;
    }

    var date = new Date();
    date.setYear(year.value);
    date.setMonth(mon.value);
    var l = getDaysInMonth(year.value, mon.value);
    var day = mday.value;

    clearSelect(mday);
    var w = 0;
    for (i = 0; i < l; i++) {
        date.setFullYear(year.value, mon.value - 1, i + 1);
        w = date.getDay();
        var o = document.createElement('option');
        o.value = getLeadingZero(i + 1);
        o.text = o.value + ' - ' + week[w];
        //alert(o.text);
        if (i == (day - 1)) o.selected = true;
        if (app.IsIE) {
            mday.add(o);
        } else {
            mday.options.add(o);
        }
    }
}
function getDaysInMonth(year, month) {
    var m = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
    if (month != 2) return m[month - 1];
    if (year % 4 != 0) return m[1];
    if (year % 100 == 0 && year % 400 != 0) return m[1];
    return m[1] + 1;
}
function clearSelect(e) {
    var first = e.options[0].innerHTML;
    if (first) {
        // Form does not allow selection of a blank date. Drop all existing options.
        e.options.length = 0;
    } else {
        // Form allows selection of a blank date. First option is blank. Keep it.
        e.options.length = 1;
    }
}
function getLeadingZero(n) {
    if (n < 10) n = '0' + n;
    return n;
}

See http://www.mattkruse.com/javascript/calendarpopup/for a different approach, which pops up a calendar. It is possible to integrate the two, feeding the results from the popup calendar back into the selectboxes.

请参阅http://www.mattkruse.com/javascript/calendarpopup/了解另一种弹出日历的方法。可以将两者结合起来,将弹出日历的结果反馈回选择框。

Remember that people can disable javascript and do all sorts of weird stuff on the client side, so server-side validation still matters.

请记住,人们可以禁用 javascript 并在客户端做各种奇怪的事情,因此服务器端验证仍然很重要。

回答by Sushil Jaiswar

jQuery and another JavaScript frameworks are present which would do the job.

jQuery 和另一个 JavaScript 框架可以完成这项工作。

回答by Martin Bean

You can't. You'll need a client-side solution for that.

你不能。为此,您需要一个客户端解决方案。

PHP deals with processing data, so you would have a JavaScript-powered date-picker where the user selects the date, and then you would have PHP save that selected date in say, a database, on submission of a form.

PHP 处理数据处理,因此您将拥有一个由 JavaScript 驱动的日期选择器,用户可以在其中选择日期,然后您可以让 PHP 在提交表单时将所选日期保存在数据库中。