How to convert string to date format using js

Source: Internet
Author: User

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.

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.