How to convert Javascript Date formatting in dd/mm/yyyy

583 Views Asked by At

I have this javascript code and this work fine on my computer if the date is insered in this format: yyyy-mm-dd, but on linux server (shared hosting), work fine if the date is insered in this format: mm/dd/yyyyy

The code is this:

<html>
<head>
<script type="text/javascript">
function findDiff(){
var bl_data_checkin= document.getElementById("bl_data_checkin").value;
var bl_data_checkout= document.getElementById("bl_data_checkout").value;
var date1 = new Date(bl_data_checkin);
var date2=new Date(bl_data_checkout);

var ONE_DAY = 1000 * 60 * 60 * 24
var d1 = date1.getTime()
var d2 = date2.getTime()
var diff = Math.abs(d1 - d2)
document.getElementById("bl_giorni_permanenza").value=Math.round(diff/ONE_DAY);
}
</script>
</head>
<body>
<pre>
Enter Date1(yyyy-mm-dd): <input type="text" name="bl_data_checkin" id="bl_data_checkin" />
Enter Date2(yyyy-mm-dd): <input type="text" name="bl_data_checkout" id="bl_data_checkout" onBlur="findDiff();" />
Number of bl_giorni_permanenza: <input type="text" name="bl_giorni_permanenza" id="bl_giorni_permanenza" />

</pre>
</body>
</html>

How to set the format dd/mm/yyyy in the javascript code?

Thanks

1

There are 1 best solutions below

0
On

Javascript Date have 4 constructors, as following:

new Date(); // current date
new Date(value); // int value representing a date since 1 January 1970 00:00:00 UTC 
new Date(dateString); // using Date.parse();
new Date(year, month [, day, hour, minute, second, millisecond]); // see my example


function parseDate(stringDate){
    var d = stringDate.split("/");
    return new Date(d[2], d[1]-1, d[0];
}

You're using the 3rd, I really don't know how to use correctly. I'm think this construtor format depends of machine idiom, so you can read more here:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date

Try to use the 4st constructor, or take a look here to know how to use Date.parse() https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/parse