Home>Article>Web Front-end> How to convert string to date type in javascript

How to convert string to date type in javascript

青灯夜游
青灯夜游 Original
2021-04-07 14:44:28 15685browse

In javascript, you can use the Date object to convert a string into a date type. The syntax format is "new Date (string date type)"; the Date object is used to process dates and times, and the date will be automatically converted. and time are saved to their initial values.

How to convert string to date type in javascript

The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.

javascript converts string to date type

var str = "2021-4-7 12:12:12"; var d = new Date(str); console.log(d); console.log(d.getTime());

Console output:

console.log(d);Displayed as:

Wed Apr 07 2021 12:12:12 GMT+0800 (中国标准时间)

consolle.log(d.getTime());Convert time into milliseconds, displayed as:

1617768732000

How to convert string to date type in javascript

Through this method, you can calculate the following questions

Write a js program and enter your birth date:

(1) Calculate your current existence in this How many days in the world.

(2) Calculate how many days you will have until you get the disease if you live to be 100 years old.

Idea:

1. The user enters a birthday string;

2. Convert the string to Date;

3. Create a Date Indicates the current time;

4. Convert both times into milliseconds and use the getTime() method

5. Subtract the milliseconds of your birthday from today’s milliseconds to calculate how many milliseconds you have lived.

6. Convert milliseconds to days

For more programming-related knowledge, please visit:Programming Video! !

The above is the detailed content of How to convert string to date type in javascript. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn