Parse ONLY a time string with DateJS

牧云@^-^@ 提交于 2019-11-30 13:06:31

Shortly after asking my question, I discovered that Date.parseExact() can take an array of format strings. Somehow I'm missed that. I managed to get something working with the following code:

function validateTime(input) {
    return Date.parseExact(input, [
            "H:m",
            "h:mt",
            "h:m t",
            "ht","h t"]) != null ||
        Date.parseExact(input, [
            "h:mtt",
            "h:m tt",
            "htt","h tt"]) != null;
};

Note that some formats don't seem to be able to be included together at the same time, which is why I split them into two separate parseExact() calls. In this case, I couldn't include any string that contained a single t in it with format strings that contained a double tt in it.

The additive approach seems cumbersome. Takes away the beauty of DateJS in my opinion. I needed the same solution and decided to just sneakily append the date in front of my input string before parsing with DateJS:

var parsed = Date.parse(Date.today().toString('M/d/yyyy') + ' ' + this.value);

if (parsed) {
  alert(parsed.toString('h:mm tt'));
}

Now DateJS will not be sniffing around for any of its date-part parsing patterns, as you have already subbed it in.

Hope this helps someone!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!