将字符串 dd-MMM-yyyy 解析为没有库的日期对象 JavaScript

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

Parse String dd-MMM-yyyy to Date Object JavaScript without Libraries

javascriptparsingdate

提问by Naresh Raj

For Example:

例如:

var dateStr = "21-May-2014";

I want the above to be into a valid Date Object.

我希望上述内容成为有效的日期对象。

Like, var strConvt = new Date(dateStr);

喜欢, var strConvt = new Date(dateStr);

回答by RobG

You need a simple parsing function like:

您需要一个简单的解析函数,例如:

function parseDate(s) {
  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};
  var p = s.split('-');
  return new Date(p[2], months[p[1].toLowerCase()], p[0]);
}

console.log(parseDate('21-May-2014'));  //  Wed 21 May 00:00:00 ... 2014