Home > Web Front-end > JS Tutorial > How to Convert \'dd-mm-yyyy\' Strings to JavaScript Date Objects?

How to Convert \'dd-mm-yyyy\' Strings to JavaScript Date Objects?

Susan Sarandon
Release: 2024-11-23 13:56:14
Original
780 people have browsed it

How to Convert

Converting dd-mm-yyyy Strings to Date Objects in JavaScript

The task at hand is to convert a string in the format "dd-mm-yyyy" to a Date object using JavaScript. The function new Date(string) fails when attempting this conversion due to the presence of the '-' symbol. To overcome this challenge, several solutions are available.

1. Split on "-"

One approach is to split the string into its three components: day, month, and year. This can be achieved using the split("-") method:

var from = $("#datepicker").val().split("-");
var f = new Date(from[2], from[1] - 1, from[0]);
Copy after login

2. Use Regular Expressions

Regular expressions can be used to extract the day, month, and year from the string:

var date = new Date("15-05-2018".replace( /(\d{2})-(\d{2})-(\d{4})/, "//"));
Copy after login

3. Refactor into a Function

If the conversion is required multiple times, it is advisable to create a reusable function:

function toDate(dateStr) {
  var parts = dateStr.split("-");
  return new Date(parts[2], parts[1] - 1, parts[0]);
}
Copy after login

This function can be used as follows:

var from = $("#datepicker").val();
var f = toDate(from);
Copy after login

4. Modern JavaScript (ES6)

In ES6, array destructuring can be used to extract the components:

const toDate = (dateStr) => {
  const [day, month, year] = dateStr.split("-");
  return new Date(year, month - 1, day);
};
Copy after login

The above is the detailed content of How to Convert \'dd-mm-yyyy\' Strings to JavaScript Date Objects?. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template