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

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

Barbara Streisand
Barbara StreisandOriginal
2024-11-19 13:16:02503browse

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

Convert dd-mm-yyyy String to Date

In JavaScript, converting a string in dd-mm-yyyy format to a date object is straightforward, but certain considerations must be taken.

Issue with Direct Conversion

When using new Date(string) with a dd-mm-yyyy string, you may encounter an "Invalid Date" error. This is because the '-' symbol is not recognized as a date separator.

Solutions

1. Split on "-":

Split the string into its component parts and manually construct the date object:

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

2. Use Regular Expressions:

Use a regular expression to extract the date components:

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

3. Create a Reusable Function:

For convenience, wrap the conversion logic in a reusable function:

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

4. Modern JavaScript:

If you have access to modern JavaScript features, leverage array destructuring:

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

The above is the detailed content of How to Reliably Convert dd-mm-yyyy Strings to JavaScript Date Objects?. 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