Javascript格式日期从字符串到日期格式 [英] Javascript format date from string to Date format

查看:108
本文介绍了Javascript格式日期从字符串到日期格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何从您想要的格式的字符串格式化日期?

how to format a date from a string in the format you want?

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


推荐答案

解析OP中的字符串的一个简单的函数是:

A simple function to parse the string in the OP is:

// 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]);
}

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

or if you just want to reformat the string (I guessed that you don't want the spaces between the numbers and separator):

// 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]);
}

帮助函数仅用于单数位数未填充输入。如果您有信心,他们一直是,您可以删除它。

The helper function is used just in case single digit numbers aren't padded in the input. If you're confident that they always are, you can remove it.

这篇关于Javascript格式日期从字符串到日期格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆