Using jQuery Datepicker and dateFormat, altFormat and altField with $(this)

Using jQuery Datepicker, I can’t get dateFormat, altFormat and altField to work correctly and output variables formatted as altFormat and using jQuery $(this)?

In the example below, the text input to the datepicker shows i.e., 20241218, while the console.logs shows i.e., Date Thu Dec 26 2024 00:00:00 GMT-0700. I’m trying to get the varibles startDate and endDate updated each time a date is selected by the user so that the variables in the format yymmdd can be used in a URL query string.

I realize that datepicker("option", "minDate", startDate) in the second and third function blocks seems to overwrite the options in the first function .datepicker({dateFormat: "MM dd, yy", altFormat: "yymmdd", altField: "#start_date_picker"}). But what I’ve tried throws Javascript errors.

The difference seems to have something to do with using $(this)this when generating the variables startDate and endDate in the second and third function blocks.

How can I use dateFormat, altFormat and altField so that they work? And output startDate and endDate in the format yymmdd?

https://jsfiddle.net/b302qwhd/

$(function() { 
            $("#start_date_picker")
            .datepicker({dateFormat: "MM dd, yy",
            altFormat: "yymmdd", altField: "#start_date_picker"});
            $("#end_date_picker")
            .datepicker({dateFormat: "MM dd, yy",
            altFormat: "yymmdd", altField: "#end_date_picker"});
            }); 

        $('#start_date_picker').on("change",function(){ 
            startDate = $(this).
            datepicker('getDate'); 
            $("#end_date_picker").
            datepicker("option", "minDate", startDate); 
            console.log(startDate);
        }) 

        $('#end_date_picker').on("change",function(){ 
            endDate = $(this).
            datepicker('getDate'); 
            $("#start_date_picker").
            datepicker("option", "maxDate", endDate); 
            console.log(endDate);

        });