The method of realizing the date format of the string conversion by JS _javascript tips

Source: Internet
Author: User
Tags getdate

This article illustrates the method of JS to implement the date format of string conversion. Share to everyone for your reference. The specific analysis is as follows:

We all know that JS is based on the results to determine the data type.
Of course, we can also transform, the following I will introduce two types of JS string type conversion to date types of methods,
My personal favorite is the first method.
Do you have any other good way to share it.

1.eval method Conversion method,---Recommended to use this method

I've written a way, everybody. Call directly

<script type= "Text/javascript" >
//String date format, strdate string function to be converted to date format
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 approach is to use split-fraction groups. This is not recommended because the date format is not flexible
Methods are as follows

<script type= "Text/javascript" > 
//String date format, strdate string function to convert to date format 
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 ("2012-9-20 19:46:18")); 
</script> 

The effect is as follows

I hope this article will help you with your JavaScript programming.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.