Js implements the string to date format method, js Date Format

Source: Internet
Author: User

Js implements the string to date format method, js Date Format

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.

<Script type = "text/javascript"> // convert string to date format. function getDate (strDate) is a string to be converted to date format) {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:

<Script type = "text/javascript"> // convert string to 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.

Related Article

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.