How could I convert the date format in the input "date1" from "dd/mm/yy" to the input "date2" in the format "mm/dd/yyyy" with Javascript or jQuery:
<input id="date1" type="text" value="25/12/21" >
<input id="date2" type="text" value="12/25/2021" >
I tried to do this but it doesn't work:
var today = new Date($('#date1').val());
var dd = today.getDate();
var mm = today.getMonth() 1;
var yyyy = today.getFullYear();
if(dd<10)
{
dd='0' dd;
}
if(mm<10)
{
mm='0' mm;
}
var converted = mm '/' dd '/' yyyy;
$('#date2').val(converted);
CodePudding user response:
You can split the value by a /
to get the month, date and year.
var s = $('#date1').val().split('/')
$('#date2').val(`${s[1]}/${s[0]}/20${s[2]}`)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="date1" type="text" value="25/12/21" >
<input id="date2" type="text" value="12/25/2021" >
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
CodePudding user response:
You can simply use split
and array destructing
to get the desired result
const [dd, mm, yy] = document.querySelector("#date1").value.split('/');
document.querySelector("#date2").value = `${mm}/${dd}/20${yy}`
<input id="date1" type="text" value="25/12/21">
<input id="date2" type="text" value="12/25/2021">
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
CodePudding user response:
you need to swap between mm and dd. like that:
var converted = dd '/' mm '/' yyyy;