Javascript格式日期从字符串到日期格式
如何将字符串中的日期格式化为所需格式Javascript格式日期从字符串到日期格式,javascript,date,Javascript,Date,如何将字符串中的日期格式化为所需格式 var dateString = "31/05/2014 12:53:51"; // function only accepts dates in the format "yyyy / mm / dd" var date = new Date (dateString); 最简单的方法是使用类似的第三方库 使用moment.js的示例代码: var date = moment("31/05/2014 12:53:51", "DD/MM/YYYY HH:
var dateString = "31/05/2014 12:53:51";
// function only accepts dates in the format "yyyy / mm / dd"
var date = new Date (dateString);
最简单的方法是使用类似的第三方库 使用moment.js的示例代码:
var date = moment("31/05/2014 12:53:51", "DD/MM/YYYY HH:mm:ss").toDate();
解析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]);
}
或者,如果您只想重新格式化字符串(我猜您不需要数字和分隔符之间的空格):
//返回“yyyy/mm/dd”格式的日期
//需要格式为d/m/y h:m:s的字符串
//分隔符不重要,顺序重要
函数重新格式化日期{
//用于格式化单个数字的帮助程序
函数z(n){return(nFirst),将字符串解析为其组成部分。在中使用then来生成日期。然后使用诸如等方法来构造所需的任何格式。
// 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]);
}