Javascript convert date format from "dd/mm/yy" to "mm/dd/yyyy"

Advertisements

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);

>Solution :

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" >

Leave a ReplyCancel reply