How to convert string to date format using js
This document describes how to convert a string to a date format in JavaScript. Share it with you for your reference. The specific analysis is as follows:
As we all know, JS determines the data type based on the results.
Of course, we can also convert it. Next I will introduce two methods for converting the JS string type to the date type,
I personally prefer the first method.
You can share some other good methods.
1. eval method conversion method --- this method is recommended
I wrote a method. You can call it directly.
?
1 2 3 4 5 6 7 8 9 10 |
<Script type = "text/javascript"> // Convert string to date format. strDate must be a string in date format. Function getDate (strDate ){ Var date = eval ('new Date ('+ strDate. replace (/\ d + (? =-[^-] + $ )/, Function (a) {return parseInt (a, 10)-1 ;}). match (/\ d +/g) + ')'); Return date; } // Test Alert (getDate ("2012-05-09 ")); </Script> |
2. The second method is to split the array. It is not recommended because the date format is not flexible.
The method is as follows:
?
1 2 3 4 5 6 7 8 9 10 11 12 13 |
<Script type = "text/javascript"> // Convert string to date format. strDate must be a string in date format. 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; } // Test Alert (getDate ("19:46:18 ")); </Script> |
The effect is as follows:
I hope this article will help you design javascript programs.