我想解析日期
var newDateTime = new Date(Date.parse($("#SelctedCalendarDay").val()));
$("#SelctedCalendarDay").val()
值是2014年10月14日的字符串。当日期为2014年10月14日时,它将正确解析。
那么,我该如何解析2014年10月14日这一日期?
最佳答案
我不确定您使用的是哪种语言(荷兰语?),所以我将使用英语,您可以轻松地替换任何您喜欢的语言。您可以使用以下方法解析日期字符串,例如2014年10月14日:
function parseDMMMY(s) {
// Split on . - or / characters
var b = s.split(/[-.\/]/);
// Months in English, change to whatever language suits
var months = {jan:0, feb:1, mar:2, apr:3, may:4, jun:5,
jul:6, aug:7, sep:8, oct:9, nov:10, dec:11};
// Create a date object
return new Date(b[2], months[b[1].toLowerCase()], b[0]);
}
console.log(parseDMMMY('14-Oct-2014')); // Tue Oct 14 2014 00:00:00
请注意,上面将创建一个本地日期对象。它不对值进行任何验证,因此,如果您给它一个像2014年6月31日这样的字符串,您将获得一个2014年7月1日的Date对象。添加验证很容易(需要多一行代码),但是如果您只知道将有效字符串传递给函数,则可能不需要这样做。