Home >Web Front-end >JS Tutorial >How to convert time string to time in javascript

How to convert time string to time in javascript

coldplay.xixi
coldplay.xixiOriginal
2021-04-30 16:27:196839browse

Javascript method to convert a time string into a time: 1. Construct a Date object based on the number of milliseconds, the code is [var date = new Date(timestamp)]; 2. Format the date, the code is [dateTime = date.toLocaleString].

How to convert time string to time in javascript

The operating environment of this tutorial: Windows 7 system, JavaScript version 1.8.5, DELL G3 computer.

Javascript method to convert time string into time:

For time string format: "2017-03-03 12:23:55";

IE: Display invalid date

new Date("2017-03-3 12:23:55")
//[date] Invalid Date[date] Invalid Date

Chrome and FireFox: Correct display

new Date("2017-03-3 12:23:55")
//Fri Mar 03 2017 12:23:55 GMT+0800 (中国标准时间)

Resolve the difference:

The time string format is uniformly converted to: "2017 /03/03 12:23:55";

var date = '2015-03-05 17:59:00';
date = date.substring(0,19);    
date = date.replace(/-/g,'/'); 
var timestamp = new Date(date).getTime();
document.write(timestamp);
// 根据毫秒数构建 Date 对象
var date = new Date(timestamp);
// 格式化日期
dateTime = date.toLocaleString();
alert(dateTime);

Related free learning recommendations: javascript video tutorial

The above is the detailed content of How to convert time string to time 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