Home >Web Front-end >JS Tutorial >How to Convert \'dd-mm-yyyy\' Strings to JavaScript Date Objects?
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]);
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})/, "//"));
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]); }
This function can be used as follows:
var from = $("#datepicker").val(); var f = toDate(from);
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); };
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!