Home >Web Front-end >JS Tutorial >How to Convert a dd-mm-yyyy String to a Date Object in JavaScript?

How to Convert a dd-mm-yyyy String to a Date Object in JavaScript?

Susan Sarandon
Susan SarandonOriginal
2024-12-01 07:22:15869browse

How to Convert a dd-mm-yyyy String to a Date Object in JavaScript?

How to Convert a dd-mm-yyyy String to a Date in JavaScript

In JavaScript, converting a string representing a date in the dd-mm-yyyy format to a Date object can be challenging due to the presence of hyphen symbols "-" as separators.

One common approach is to split the string into its components using the "-" as a delimiter and then manually create a Date object using the split parts. For example:

var dateString = "15-05-2018";
var dateParts = dateString.split("-");
var date = new Date(dateParts[2], dateParts[1] - 1, dateParts[0]);

Alternatively, regular expressions can be used to extract the date parts from the string:

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

In cases where simplicity and performance are prioritized, it may be more convenient to define a reusable function to handle the conversion:

function toDate(dateString) {
  var dateParts = dateString.split("-");
  return new Date(dateParts[2], dateParts[1] - 1, dateParts[0]);
}

var date = toDate("15-05-2018");

For JavaScript versions supporting destructuring, a more concise approach is available:

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

const date = toDate("15-05-2018");

By selecting the appropriate method, developers can easily convert dd-mm-yyyy strings to Date objects, ensuring accurate date handling in their JavaScript applications.

The above is the detailed content of How to Convert a dd-mm-yyyy String to a Date Object 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