Convert dd-mm-yyyy String to Date
The inability to parse a dd-mm-yyyy string into a valid date object using JavaScript's Date constructor is primarily due to the presence of the '-' symbol, which is not recognized by the constructor. To overcome this, alternative approaches are required.
Solution: Split on "-"
One solution is to split the string into its individual components using the '-' symbol as a delimiter and then create a new Date object using the day, month, and year values:
var from = $("#datepicker").val().split("-") var f = new Date(from[2], from[1] - 1, from[0])
Solution: Use Regex
Regular expressions can also be used to extract the individual date components and construct a valid date string:
var date = new Date("15-05-2018".replace( /(\d{2})-(\d{2})-(\d{4})/, "//"))
Recommendation: Split on "-"
While both approaches are valid, the "split on -" method is arguably more specific and efficient for this particular task, as it directly targets the known format of the input string without relying on potentially more complex regex matching.
Reusability
If this conversion is performed multiple times in the code, it is advisable to encapsulate it in a function for reusability and maintainability:
function toDate(dateStr) { var parts = dateStr.split("-") return new Date(parts[2], parts[1] - 1, parts[0]) }
Using the function:
var f = toDate($("#datepicker").val()) var t = toDate($("#datepickertwo").val())
Modern JavaScript
For modern JavaScript environments, array destructuring can simplify the code:
const toDate = (dateStr) => { const [day, month, year] = dateStr.split("-") return new Date(year, month - 1, day) }
The above is the detailed content of How Can I Convert a dd-mm-yyyy String to a JavaScript Date Object?. For more information, please follow other related articles on the PHP Chinese website!