skip to Main Content

I want the page to automatically set the current date in yyyy-mm-dd format in this bar, where a click expands the calendar with check data.

Now it looks like this: (https://i.sstatic.net/vd0mPro7.png) and I can only manually select the date on the calendar. But I want to set date format in yyyy-mm-dd and I don’t know how change it.

2

Answers


  1. <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Date Input</title>
        <script>
            document.addEventListener('DOMContentLoaded', (event) => {
                const dateInput = document.getElementById('datePicker');
                
                // Function to format date to yyyy-mm-dd
                function formatDateToYYYYMMDD(date) {
                    const year = date.getFullYear();
                    const month = String(date.getMonth() + 1).padStart(2, '0'); // Months are zero-based
                    const day = String(date.getDate()).padStart(2, '0');
                    return `${year}-${month}-${day}`;
                }
    
                // Set current date as default
                const currentDate = new Date();
                dateInput.value = formatDateToYYYYMMDD(currentDate);
            });
        </script>
    </head>
    <body>
        <input type="date" id="datePicker">
    </body>
    </html>
    

    In HTML it contains the ID datePicker in the input feild and the JS in the script runs when the page is fully loaded and the current format of the date will be yyy-mm-dd

    Login or Signup to reply.
  2. You can just add this small script here

    <input type="date" id="dateInput">
    
    <script>
        document.getElementById('dateInput').valueAsDate = new Date();
    </script>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search