Chi*_*ani 42
您可以使用HTML5输入日期的最小和最大属性
HTML5代码
<input type="date" name="bday" min="2014-05-11" max="2014-05-20">
Run Code Online (Sandbox Code Playgroud)
编辑
你需要使用jQuery来实现它
jQuery代码
$(function(){
var dtToday = new Date();
var month = dtToday.getMonth() + 1;
var day = dtToday.getDate();
var year = dtToday.getFullYear();
if(month < 10)
month = '0' + month.toString();
if(day < 10)
day = '0' + day.toString();
var maxDate = year + '-' + month + '-' + day;
$('#txtDate').attr('max', maxDate);
});
Run Code Online (Sandbox Code Playgroud)
说明 HTML5输入日期的最大属性采用两位数格式的月份和日期.
例:5(月)无效,而05(月)有效例:1(日)无效,而01(日)有效
所以我在下面添加了代码
if(month < 10)
month = '0' + month.toString();
if(day < 10)
day = '0' + day.toString();
Run Code Online (Sandbox Code Playgroud)
检查我的更新小提琴
参考小提琴演示
Jua*_*ank 17
为了建立@Chirag Vidani的答案,可以用更少的行生成日期:
var now = new Date(),
minDate = now.toISOString().substring(0,10);
$('#my-date-input').prop('min', minDate);
Run Code Online (Sandbox Code Playgroud)
Pai*_*uin 11
这是一个 PHP 解决方案,它获取今天的日期并将其设置为最大值。
<input type="date" name="bday" max="<?php echo date("Y-m-d"); ?>">
Run Code Online (Sandbox Code Playgroud)
这会将其设置为日期和月份的正确两位数格式。 https://www.php.net/manual/en/function.date.php
其他一些人提出了有关将最大日期设置为当前日期的问题。建议的答案涉及使用 JavaScript。但我的解决方案是使用服务器端语言来生成输入的 max 参数。我知道OP没有询问服务器端方法。但这个解决方案非常适合我使用 C# Razor 作为服务器语言。
在服务器上我写:
@Html.TextBox("CurrentDate",
Model.CurrentDate.ToString("yyyy-MM-dd"),
new {
@class = "form-control",
@type = "date",
max = DateTime.Now.ToString("yyyy-MM-dd")
})
Run Code Online (Sandbox Code Playgroud)
然后MVC输出这个Html:
<input class="form-control" id="CurrentDate" name="CurrentDate"
type="date" max="2016-11-10" value="2016-11-10">
Run Code Online (Sandbox Code Playgroud)
对于其他服务器语言,方法是使用服务器的日期类似地生成 max 参数,如果您的要求是使用客户端的日期,则该方法可能有效也可能无效。对于我的情况,服务器的日期是所需要的,因为那是数据的存储位置。