将 DatePicker 文本框转换为 javascript 日期
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13103987/
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
Convert DatePicker textbox into javascript Date
提问by Scott Selby
I have a datepicker in 2 textboxes , in am trying to add the value of these text boxes to a function that needs a valid Javascript Date.
我在 2 个文本框中有一个日期选择器,我正在尝试将这些文本框的值添加到需要有效 Javascript 日期的函数中。
This is the part of the function - start is a Date
这是函数的一部分 - start 是一个日期
else if (daystosearch == 'custom') {
start.setDate(Date.parse($('#<%= tStartDate.ClientID %>').val()));
end.setDate(Date.parse($('#<%= tEndDate.ClientID %>').val()));
}
Date.Parse will not work , because value of the textbox is "10/29/2012" which is not a parsable date. How can I use start.setDate
and get the value of the textboxes date ?
Date.Parse 将不起作用,因为文本框的值为“10/29/2012”,这不是可解析的日期。如何使用start.setDate
和获取文本框日期的值?
采纳答案by Ian
If the value of the textbox is something like "10/29/2012", you should be able to use:
如果文本框的值类似于“10/29/2012”,您应该可以使用:
var new_start = new Date($('#<%= tStartDate.ClientID %>').val());
But if you're trying to use setDate
, the value that it accepts is an integer from 1-31, so you need to use getDate
on the new Date object, like:
但是,如果您尝试使用setDate
,它接受的值是 1-31 之间的整数,因此您需要getDate
在新的 Date 对象上使用,例如:
var new_start = new Date($('#<%= tStartDate.ClientID %>').val());
start.setDate(new_start.getDate());
回答by Tallmaris
Use $(selector).datepicker("getDate")
and then .getDate()
to grab the day. In your case:
使用 $(selector).datepicker("getDate")
然后.getDate()
抓住这一天。在你的情况下:
start.setDate($('#<%= tStartDate.ClientID %>').datePicker("getDate").getDate());
As the first comment says, this will give you a Date object directly, regardless of the string format used in the textbox. Have a look at the API documentation:)
正如第一条评论所说,无论文本框中使用的字符串格式如何,这都会直接为您提供一个 Date 对象。看看API 文档:)
Edit: as ianpgall noted, you will need to also use getDate() to grab the day number.
编辑:正如 ianpgall 所指出的,您还需要使用 getDate() 来获取日期。
回答by jd_7
Use Utility functions from datepicker http://docs.jquery.com/UI/Datepicker/parseDate
使用 datepicker http://docs.jquery.com/UI/Datepicker/parseDate 中的实用函数
$.datepicker.parseDate('yy-mm-dd', '2007-01-26');