以“-”分割
将字符串解析成你需要的部分:
var from = $("#datepicker").val().split("-")
var f = new Date(from[2], from[1] - 1, from[0])
使用正则表达式
var date = new Date("15-05-2018".replace( /(\d{2})-(\d{2})-(\d{4})/, "$2/$1/$3"))
为什么不使用正则表达式?
因为您知道您将处理由三部分组成的字符串,用连字符分隔。
但是,如果您要在另一个字符串中查找相同的字符串,则可以使用正则表达式。
重复使用
因为您在示例代码中多次执行此操作,并且可能在代码库的其他地方,将其包装在一个函数中:
function toDate(dateStr) {
var parts = dateStr.split("-")
return new Date(parts[2], parts[1] - 1, parts[0])
}
用作:
var from = $("#datepicker").val()
var to = $("#datepickertwo").val()
var f = toDate(from)
var t = toDate(to)
或者如果你不介意在你的函数中使用 jQuery:
function toDate(selector) {
var from = $(selector).val().split("-")
return new Date(from[2], from[1] - 1, from[0])
}
用作:
var f = toDate("#datepicker")
var t = toDate("#datepickertwo")
现代 JavaScript
如果你能够使用更现代的 JS,数组解构也是一个不错的选择:
const toDate = (dateStr) => {
const [day, month, year] = dateStr.split("-")
return new Date(year, month - 1, day)
}