21

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

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

4

6 回答 6

44

使用 moment.js,您可以使用String+Format 构造函数创建一个 moment 对象:

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

然后,您可以使用toDate() 方法将其转换为 JavaScript 日期对象:

var jsDate = momentDate.toDate();
于 2015-01-17T17:46:58.430 回答
8

一个更好的解决方案,我现在使用 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");
于 2015-01-18T05:34:02.533 回答
7
new Date("2015-01-16T22:15:00")

请参阅Date.parse()

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

moment("2015-01-16 22:15:00").toDate();
于 2015-01-17T17:42:01.067 回答
2

我试图使用 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);
}
于 2015-01-17T18:11:30.457 回答
1

如果您确定它是所需的格式并且不需要错误检查,您可以使用 split 手动解析它(并且可以选择替换)。我需要在我的项目(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]) ; 
于 2017-07-19T22:57:37.543 回答
0

有点烦人,但在没有任何依赖的情况下自己编写解析方法并不难。正则表达式非常适合根据一种或多种日期格式检查输入。不过,现在提供的格式中的日期“正常工作”。即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);
}
于 2021-12-06T13:01:48.043 回答