Home  >  Article  >  Web Front-end  >  JS implements string conversion to date format

JS implements string conversion to date format

小云云
小云云Original
2018-03-28 17:27:024776browse

This article mainly shares with you js to convert string to date format, mainly in the form of code, I hope it can help everyone.

1. eval method conversion method, --- it is recommended to use this method

I wrote a method, if you want it, call it directly

<script type="text/javascript">
//字符串转日期格式,strDate要转为日期格式的字符串
function getDate(strDate){
  var date = eval(&#39;new Date(&#39; + strDate.replace(/\d+(?=-[^-]+$)/, 
   function (a) { return parseInt(a, 10) - 1; }).match(/\d+/g) + &#39;)&#39;);
  return date;
}
//测试
alert(getDate("2012-05-09"));
</script>

2. The second method This is done by splitting the array. It is not recommended to use it this way, because the date format is inflexible
The method is as follows

<script type="text/javascript"> 
//字符串转日期格式,strDate要转为日期格式的字符串 
function getDate(strDate) { 
  var st = strDate; 
  var a = st.split(" "); 
  var b = a[0].split("-"); 
  var c = a[1].split(":"); 
  var date = new Date(b[0], b[1], b[2], c[0], c[1], c[2]);
  return date; 
} 
//测试 
alert(getDate("2012-9-20 19:46:18")); 
</script>


The effect is as follows,

Related recommendations:

Detailed explanation of method examples using js to convert string to date format

The above is the detailed content of JS implements string conversion to date format. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn