Home > other >  How To Change Date Format Received From Input Field Using Javascript?
How To Change Date Format Received From Input Field Using Javascript?

Time:01-13

I Have a form where I received input from users using the form. Based on user input I changed the image src.

<center><span>-: Select Your City :-</span><br>
      <form action="" method="POST">
            <select name="city">
                  <option value="">Select city...</option>
                  <option value="de" selected>Delhi</option>
                  <option value="mu">Mumbai</option>
                  <option value="lc">Lucknow</option>
            </select>
            <br><br>
            <span>-: Select Date :-</span>
            <br>
            <input type="date" name="old" value="2023-01-13" min="2021-01-01" max="2023-01-13" required />
            <br><br>
            <input type="submit" value="Go" />
      </form>
</center>

<img src="https://image.example.com/images/13012023/13012023-de-1.jpg"><br>
<img src="https://image.example.com/images/13012023/13012023-de-2.jpg"><br>
<img src="https://image.example.com/images/13012023/13012023-de-3.jpg"><br>
<img src="https://image.example.com/images/13012023/13012023-de-4.jpg"><br>
<img src="https://image.example.com/images/13012023/13012023-de-5.jpg"><br>


<script>
      const today = new Date();
      const year = today.getFullYear();
      const month = String(today.getMonth()   1).padStart(2, '0');
      const day = String(today.getDate()).padStart(2, '0');

      // Get the form elements
      const form = document.querySelector('form');
      const citySelect = form.querySelector('select[name="city"]');
      const dateInput = document.querySelector('input[type="date"]');
      dateInput.value = `${year}-${month}-${day}`;
      dateInput.max = `${year}-${month}-${day}`;

      // Get the selected city and date values
      const city = citySelect.value;
      const date = dateInput.value;

      // Get all the img elements
      const images = document.querySelectorAll('img');

      // Add an event listener to the form that will run a function
      // when the form is submitted
      form.addEventListener('submit', (event) => {
            // Prevent the form from submitting and refreshing the page
            event.preventDefault();

            // Get the selected city and date values
            const city = citySelect.value;
            const date = dateInput.value;

            // Get all the img elements
            const images = document.querySelectorAll('img');

            // Update the src attribute of each img element
            images.forEach((image, index) => {
                  const imageNumber = String(index   1);
                  image.src =
                        `https://image.example.com/images/${date.replace(/-/g, '')}/${date.replace(/-/g, '')}-${city}-${imageNumber}.jpg`;
            });
      });
</script>

Now I wanted to update the image tag src based on user input. But the problem is my code set the date in YYYYMMDD format but I want the date in DDMMYYY format to set the date in the image src.

CodePudding user response:

Just add an id to the input to get its value

Then, splitting value with "-" will be ['2023', '01', '13']

Now, you can reverse the result to be ['13', '01', '2023'] and join them adding '-'

const newDate = date.split('-').reverse().join("-");

console.log(newDate);
<center><span>-: Select Your City :-</span><br>
      <form action="" method="POST">
            <select name="city">
                  <option value="">Select city...</option>
                  <option value="de" selected>Delhi</option>
                  <option value="mu">Mumbai</option>
                  <option value="lc">Lucknow</option>
            </select>
            <br><br>
            <span>-: Select Date :-</span>
            <br>
            <input id = "date" type="date" name="old" value="2023-01-13" min="2021-01-01" max="2023-01-13" required 
            />
            <br><br>
            <input type="submit" value="Go" />
      </form>
</center>

<img src="https://image.example.com/images/13012023/13012023-de-1.jpg"><br>
<img src="https://image.example.com/images/13012023/13012023-de-2.jpg"><br>
<img src="https://image.example.com/images/13012023/13012023-de-3.jpg"><br>
<img src="https://image.example.com/images/13012023/13012023-de-4.jpg"><br>
<img src="https://image.example.com/images/13012023/13012023-de-5.jpg"><br>


<script>
      const today = new Date();
      const year = today.getFullYear();
      const month = String(today.getMonth()   1).padStart(2, '0');
      const day = String(today.getDate()).padStart(2, '0');

      // Get the form elements
      const form = document.querySelector('form');
      const citySelect = form.querySelector('select[name="city"]');
      const dateInput = document.querySelector('input[type="date"]');
      dateInput.value = `${year}-${month}-${day}`;
      dateInput.max = `${year}-${month}-${day}`;

      // Get the selected city and date values
      const city = citySelect.value;
      const date = dateInput.value;

      // Get all the img elements
      const images = document.querySelectorAll('img');

      // Add an event listener to the form that will run a function
      // when the form is submitted
      form.addEventListener('submit', (event) => {
            // Prevent the form from submitting and refreshing the page
            event.preventDefault();

            // Get the selected city and date values
            const city = citySelect.value;
            const date = dateInput.value;

            // Get all the img elements
            const images = document.querySelectorAll('img');

            // Update the src attribute of each img element
            images.forEach((image, index) => {
                  const imageNumber = String(index   1);
                  image.src =
                        `https://image.example.com/images/${date.replace(/-/g, '')}/${date.replace(/-/g, '')}-${city}-${imageNumber}.jpg`;
            });
      });
</script>

CodePudding user response:

Try this:

const date = dateInput.value;
const [year, month, day] = date.split('-');
const result = [day, month, year].join('/');
console.log(result);

CodePudding user response:

You can use the toLocaleDateString according to your requirements, for example

<script>
        var options = { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' };
        var today = new Date();
        var localDate = today.toLocaleDateString("en-uk");
        console.log(today.toLocaleDateString("en-uk")); // 13/01/2023

        localDate = localDate.split("/").join("");       
        console.log(localDate)  //13012023
 
    </script>
  • Related