简体   繁体   English

使用javascript和regex解析问题的日期

[英]Date parsing troubles with javascript and regex

So I've been trying to get a jsfiddle example with d3.js working where it say takes in a string input such as; 所以我一直在尝试用d3.js工作的jsfiddle示例,它表示接受字符串输入,如;

"8/8/2011 12:00:00 AM"

And with that string can create a Date Object from parsing out the date info with regex. 使用该字符串可以通过使用正则表达式解析日期信息来创建日期对象。

I've been using near identical regex from this one. 我一直在使用与相同的正则表达式。 The format I'm trying to capture is a simple MM/DD/YYYY with actual validation I'll do by passing it into a Date object later on. 我想要捕获的格式是一个简单的MM / DD / YYYY,我将通过稍后将其传递给Date对象来进行实际验证。

The actual regex pattern I came up with to do small validation is: 我想出的用于进行小验证的实际正则表达式模式是:

(([01]?[0-2]|[0-9])(\/)([0-2]?[0-9]|3[01])(\/)((19|20)\d{2}))

However my pattern is giving me some issues it seems with flags and matching/validating. 然而,我的模式给了我一些问题,似乎有标志和匹配/验证。 Rubular validates fine without any flags and gets all the dates matched, but will break if I put the global flag (g) on the pattern. Rubular在没有任何标志的情况下验证正常并且所有日期都匹配,但如果我将全局标志(g)放在模式上,它将会中断。 However with regex101 I need to put the global flag (g) for it to be able to match all the dates I put for test strings. 但是对于regex101,我需要为它设置全局标志(g),以便能够匹配我为测试字符串添加的所有日期。 I'm confused if the flag truly matters or not and would love some clarification. 如果国旗真的重要或者不重要,我会感到困惑,并希望得到一些澄清。

Next to my jsfiddle example which stopped giving me any alert or feedback. 我的jsfiddle示例旁边停止给我任何警报或反馈。 However I'm also having trouble getting RegEx.exec(str) to properly work like I want. 但是我也无法让RegEx.exec(str)正常工作,就像我想要的那样。 I thought I had it pushing the first entry in the array, which would be the date string I wanted. 我以为我有它推动数组中的第一个条目,这将是我想要的日期字符串。 However like I said I don't get any feedback or alerts pop-up that I have set. 但是就像我说的那样,我没有得到任何反馈或警告弹出我设置的。 According to jsfiddle my javascript is valid, so I'm at a lost. 根据jsfiddle我的javascript是有效的,所以我迷路了。

I have it all commented with the logic of what I was trying to do, but I've tried everything that I could think of and wouldn't mind someone else taking a small look and pointing out something I may have missed. 我已经对我试图做的事情的逻辑进行了评论,但是我已经尝试了所有我能想到的东西,并且不介意别人看一看,并指出我可能错过的东西。

I know this isn't using regex at all, but have you tried using the Date.parse() function in javascript? 我知道这根本没有使用正则表达式,但你尝试过在javascript中使用Date.parse()函数吗? In your case, you can do something like this: 在您的情况下,您可以这样做:

var dateString = "8/10/2011 12:00:00 AM"; // used different month to date for highlighting purposes
var date = new Date();
date.setTime(Date.parse(dateString));

date.getFullYear(); // returns 2011;
date.getMonth() // returns 7 (months are 0-11)
date.getDate(); // returns 10

More info here: MDN Date.parse() 更多信息: MDN Date.parse()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM