Home > Web Front-end > JS Tutorial > body text

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

怪我咯
Release: 2017-06-29 10:21:01
Original
1758 people have browsed it

This article mainly introduces the method of converting js to string to date format, involving javascript related skills for string and date operations, friends in need can refer to the following

The example in this article describes the method of converting string to date format in js. Share it with everyone for your reference. The specific analysis is as follows:

Everyone knows that JS determines the data type based on the result.
Of course we can also convert it. Below I will introduce two methods for converting JS string type into date type.
I personally prefer the first method.
If you have any other good methods, please share them.

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>
Copy after login

2. The second method It is the method of splitting array. It is not recommended to use this method 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>
Copy after login

The effect is as follows

The above is the detailed content of Detailed explanation of method examples using js to convert string to date format. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!