解析 Javascript 中的自定义格式的 'Date & Time' 字符串

Parse 'Date & Time' string in Javascript which are of custom format

我必须解析格式为“2015-01-16 22:15:00”的日期和时间字符串。我想将其解析为 JavaScript 日期对象。有什么帮助吗?

我尝试了一些 jquery 插件,moment.js、date.js、xdate.js。仍然没有运气。

new Date("2015-01-16T22:15:00")

参见Date.parse()

字符串必须为 ISO-8601 格式。如果要解析其他格式,请使用 moment.js.

moment("2015-01-16 22:15:00").toDate();

使用 moment.js 您可以使用 String+Format constructor:

创建矩对象
var momentDate = moment('2015-01-16 22:15:00', 'YYYY-MM-DD HH:mm:ss');

然后,您可以使用 toDate() method:

将其转换为 JavaScript 日期对象
var jsDate = momentDate.toDate();

我正在尝试使用 moment.js 人。但是因为我有这个错误,"ReferenceError: moment is not defined",我不得不暂时跳过它。我现在正在使用临时解决方法。

function parseDate(dateString) {
    var dateTime = dateString.split(" ");
    var dateOnly = dateTime[0];
    var timeOnly = dateTime[1];

    var temp = dateOnly + "T" + timeOnly;
    return new Date(temp);
}

更好的方案,我现在用的是date.js - https://code.google.com/p/datejs/

我在我的 html 页面中包含了这个脚本 -

<script type="text/javascript" src="path/to/date.js"></script>

然后我简单地解析了日期字符串“2015-01-16 22:15:00”,并将格式指定为,

var dateString = "2015-01-16 22:15:00";
var date = Date.parse(dateString, "yyyy-MM-dd HH:mm:ss");

如果您确定它是所需的格式并且不需要错误检查,您可以使用拆分(并可选地替换)手动解析它。我需要在我的项目中做类似的事情 (MM/DD/YYYY HH:mm:ss:sss) 并修改我的解决方案以适应您的格式。 注意月份减1。

var str = "2015-01-16 22:15:00"; 
//Replace dashes and spaces with : and then split on :
var strDate = str.replace(/-/g,":").replace(/ /g,":").split(":");
var aDate = new Date(strDate[0], strDate[1]-1, strDate[2], strDate[3], strDate[4], strDate[5]) ; 

有点烦人,但自己写一个没有任何依赖的解析方法并不难。正则表达式非常适合根据一种或多种日期格式检查输入。不过,目前格式中的日期 'just works'。 IE。 new Date('2015-01-16 22:15:00') 在 Firefox 中对我有用。我为一个看起来像“08.10.2020 10:40:32”的日期执行此操作,该日期不起作用,并且提供的日期可能在某些浏览器中不起作用。但是这样你就可以在不依赖内置解析方法的情况下解析它。

function getAsDate(input) {
    if (!input) return null;
    if (input instanceof Date) return input;

    // match '2015-01-16 22:15:00'
    const regexDateMatch = '^[0-9]{4}\-[0-9]{1,2}\-[0-9]{1,2}\ [0-9]{2}\:[0-9]{2}\:[0-9]{2}$';
    if(input.match(regexDateMatch)) {
        const [year, month, day, hours, minutes, seconds] = input.split(/[-: ]/).map(x => parseInt(x));
        const date = new Date(year, month, day, hours, minutes, seconds);
        return date;
    }

    // Date formats supported by JS
    return new Date(input);
}