Home > Article > Web Front-end > js method to convert string to date format_javascript skills
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('new Date(' + strDate.replace(/\d+(?=-[^-]+$)/, function (a) { return parseInt(a, 10) - 1; }).match(/\d+/g) + ')'); return date; } //测试 alert(getDate("2012-05-09")); </script>
2. The second method is to use 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
I hope this article will be helpful to everyone’s JavaScript programming design.