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

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

Susan Sarandon
Susan SarandonOriginal
2024-11-22 19:57:14370browse

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

Convert String in dd-mm-yyyy Format to Date Object in JavaScript

In attempting to convert a dd-mm-yyyy formatted string into a Date object, you may encounter "Invalid Date" errors due to the presence of '-' symbols.

Solution 1: Split on "-"

Break the string into its individual day, month, and year components:

var dateStr = $("#datepicker").val();
var dateParts = dateStr.split("-");
var date = new Date(dateParts[2], dateParts[1] - 1, dateParts[0]);

Solution 2: Use Regular Expressions (Regex)

Use a regex to extract the individual components from the string:

var regex = /(\d{2})-(\d{2})-(\d{4})/;
var date = new Date(dateStr.replace(regex, "//"));

Recommendation: Split on "-"

While regex provides more flexibility, splitting on "-" is recommended when parsing fixed-format strings because it is simpler and more efficient, especially if you are reusing the parsing logic in multiple parts of your code.

Reusability and Modern JavaScript

For reusability, you can wrap the parsing logic in a function:

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

In modern JavaScript, you can use array destructuring to simplify the parsing:

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

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