I’m currently working on a JavaScript function that extracts a date from a string and then parses it to set the start and end dates for a date filter. However, I’m encountering an issue with the date parsing part.
$("#startDateF").data("initialValue", startDateString);
$("#endDateF").data("initialValue", endDateString);
These lines are getting used in a reset button function which will retrieve these values and set the current values of the date filters back to the initialValues.
Here is the code :
var cDate = dText.match(/d{2}-d{2}-d{4}/)[0];
console.log(cDate);
let initialStartDate = new Date(cDate);
let initialEndDate = new Date(initialStartDate.getFullYear(), initialStartDate.getMonth() + 1, initialStartDate.getDate());
startDateString = formatDate(initialStartDate);
endDateString = formatDate(initialEndDate);
$("#startDateF").data("initialValue", startDateString);
$("#endDateF").data("initialValue", endDateString);
function formatDate(date) {
let day = ("0" + date.getDate()).slice(-2);
let month = ("0" + (date.getMonth() + 1)).slice(-2);
let year = date.getFullYear();
return day + "-" + month + "-" + year;
}
I tried using formatDate function to format the date but it seems it is not working correctly. When I used this method it is setting startDate and endDate to aN-aN-NaN I am expecting that the startDate is set to cDate and endDate is set to the same date but the in the next month. E.g. cDate = 16-04-2023 startDate = 16-04-2023 endDate = 16-05-2023
2
Answers
The issue with your code lies in the calculation of the initial end date. You are adding 1 to the month value without considering the case where the current month is December. Adding 1 to December (month number 11) will result in January (month number 0) of the next year. This is why you are getting unexpected values for the end date. Isnt it?
Try following code with modification, it should solve your issue.
Summary you can modify the calculation of the initial end date to handle the case of December correctly. Here’s an updated version of your code:
There are no issues on your code except when you parse the
initialStartDate
variabe The Date constructor in JavaScript does not directly accept date strings in the format ‘dd-mm-yyyy’. To create a Date object from a custom date string, you’ll need to parse the individual day, month, and year components and pass them as arguments to the constructor in the appropriate order.so basically you could just add this
and will work just fine
here is the full code tho
I hope it helps 😀