jQuery 日期选择器:将输入值设置为当前日期

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17964678/
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-26 20:17:13  来源:igfitidea点击:

Datepicker: Setting input value to current date

jqueryhtmltwitter-bootstrapdatepicker

提问by designtocode

I am using this plugin for Bootstrap, for date picking http://eternicode.github.io/bootstrap-datepicker/

我将这个插件用于 Bootstrap,用于日期选择http://eternicode.github.io/bootstrap-datepicker/

I have it working here FIDDLEBut I dont know if this is the right way to do it? Or if there's a way to do it through the plugin. I've tried to but I haven't got it right.

我在这里工作FIDDLE但我不知道这是否是正确的方法?或者如果有办法通过插件来做到这一点。我试过了,但我没有做对。

HTML:

HTML:

Date: <input type="text" name="" class="datepicker" />

Jquery:

查询:

var d = new Date();

var month = d.getMonth()+1;
var day = d.getDate();

var output =((''+month).length<2 ? '0' : '') + month +  '/' + ((''+day).length<2 ? '0' : '') + day + '/' + d.getFullYear();

$('.datepicker').datepicker();

$('.datepicker').val(output);

So I'm using Jquery to get the current date then I just fire the datepicker and then set the input value to the current date.

所以我使用 Jquery 来获取当前日期,然后我只是触发日期选择器,然后将输入值设置为当前日期。

Any other ideas or suggestions will be appreciated!

任何其他想法或建议将不胜感激!

回答by Dziad Borowy

Your method is good.

你的方法很好。

You could, however, reduce it a couple of characters - if you'd like - to something like this:

但是,您可以将其减少几个字符 - 如果您愿意 - 如下所示:

var d = new Date(),
    output = [
        ('0' + (d.getMonth() + 1)).substr(-2), 
        ('0' + d.getDate()).substr(-2), 
        d.getFullYear()
    ].join('/');

$('.datepicker').datepicker().val(output);

Also - if you're doing more work with dates - it might be a good idea to have a look at some date libraries, like date.jsor sugar.js, then you could do something like this:

另外 - 如果你正在做更多的日期工作 - 查看一些日期库可能是个好主意,比如date.jsSugar.js,那么你可以做这样的事情:

$('.datepicker').val(new Date().toString('MM/dd/yyyy'));        // date.js
$('.datepicker').val(Date.create().format('{MM}/{dd}/{yyyy}')); // sugar.js

回答by Dziad Borowy

Datepicker is initialized with current date by default. (demo)

默认情况下,Datepicker 使用当前日期进行初始化。(演示

You can set it manually too:

您也可以手动设置:

$("#datepicker").datepicker({defaultDate: new Date()}); //at initialization
$("#datepicker").datepicker("setDate",new Date());      //runtume

Setting to other dates is easy too:

设置其他日期也很容易:

$("#datepicker").datepicker("setDate","14/12/2014");

With self defined format:

使用自定义格式:

$("#datepicker").datepicker({ dateFormat: "yy-m-d" });
$("#datepicker").datepicker("setDate","14-12-4");

To get that formatted value, use:

要获取该格式化值,请使用:

$("#datepicker").datepicker().val();

Documentation here.

文档在这里。