如何将 dd/mm/yyyy 字符串转换为 JavaScript 日期对象? [英] How to convert dd/mm/yyyy string into JavaScript Date object?
问题描述
如何将格式为 23/10/2015
的日期转换为JavaScript 日期格式:
How to convert a date in format 23/10/2015
into a
JavaScript Date format:
Fri Oct 23 2015 15:24:53 GMT+0530 (India Standard Time)
推荐答案
MM/DD/YYYY 格式
如果您有 MM/DD/YYYY
格式,这是 JavaScript 的默认格式,您只需将字符串传递给 Date(string)
构造函数.它会为你解析它.
MM/DD/YYYY format
If you have the MM/DD/YYYY
format which is default for JavaScript, you can simply pass your string to Date(string)
constructor. It will parse it for you.
var dateString = "10/23/2015"; // Oct 23
var dateObject = new Date(dateString);
document.body.innerHTML = dateObject.toString();
如果您使用这种格式,那么您可以拆分日期以分别获取日、月和年,然后在另一个构造函数中使用它 - Date(year, month, day)
:
If you work with this format, then you can split the date in order to get day, month and year separately and then use it in another constructor - Date(year, month, day)
:
var dateString = "23/10/2015"; // Oct 23
var dateParts = dateString.split("/");
// month is 0-based, that's why we need dataParts[1] - 1
var dateObject = new Date(+dateParts[2], dateParts[1] - 1, +dateParts[0]);
document.body.innerHTML = dateObject.toString();
有关更多信息,您可以在 Mozilla 开发者网络.
For more information, you can read article about Date
at Mozilla Developer Network.
或者,您可以使用 moment.js
库,这可能是最受欢迎的库在 JavaScript 中解析和操作日期和时间:
Alternatively, you can use moment.js
library, which is probably the most popular library to parse and operate with date and time in JavaScript:
var dateString = "23/10/2015"; // Oct 23
var dateMomentObject = moment(dateString, "DD/MM/YYYY"); // 1st argument - string, 2nd argument - format
var dateObject = dateMomentObject.toDate(); // convert moment.js object to Date object
document.body.innerHTML = dateObject.toString();
<script src="https://momentjs.com/downloads/moment.min.js"></script>
在所有三个示例中,dateObject
变量都包含一个 Date
,代表一个时刻,可以进一步转换为任何字符串格式.
In all three examples dateObject
variable contains an object of type Date
, which represents a moment in time and can be further converted to any string format.
这篇关于如何将 dd/mm/yyyy 字符串转换为 JavaScript 日期对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!