2014-04-26 198 views
0

如何从所需格式的字符串格式化日期?Javascript格式日期从字符串到日期格式

var dateString = "31/05/2014 12:53:51"; 
// function only accepts dates in the format "yyyy/mm/dd" 
var date = new Date (dateString); 
+1

首先,将字符串解析为其组成部分。然后在[* Date构造函数*](http://ecma-international.org/ecma-262/5.1/#sec-15.9.3.1)中使用来创建日期。然后使用[* getFullYear *](http://ecma-international.org/ecma-262/5.1/#sec-15.9.5.10),[* getMonth *](http://ecma-international.org/)等方法ecma-262/5.1 /#sec-15.9.5.12)等来构建你想要的任何格式。 – RobG

回答

0

一个简单的函数来解析在OP字符串为:

// Return a Date object 
// Expects string in format d/m/y h:m:s 
// Separator is not important, order is 
function parseDate(s) { 
    var b = s.split(/\D+/); 
    return new Date(b[2], --b[1], b[0], b[3], b[4], b[5]); 
} 

,或者如果你只是想重新格式化字符串(我猜测你不想要数字和分隔符之间的空格):

// Return a date in "yyyy/mm/dd" format 
// Expects string in format d/m/y h:m:s 
// Separator is not important, order is 
function reformatDate(s) { 
    // Helper to format single digit numbers 
    function z(n) {return (n<10? '0' : '') + +n;} 
    var b = s.split(/\D+/); 
    return b[2] + '/' + z(b[1]) + '/' + z(b[0]); 
} 

帮助函数只用于我在输入中没有填充单个数字的情况。如果你确信他们始终是,你可以将其删除。

0

最简单的方法是使用一些第三方库,如Moment.js

代码的例子使用moment.js:

var date = moment("31/05/2014 12:53:51", "DD/MM/YYYY HH:mm:ss").toDate();