I use the Date()
function to convert MySQL Date to the JS Date object.
Following is the code of how I was doing it:
var a = "2019-03-12 12:30:03"; //MySQL Date
function MySQLToDate(dateString) {
if (typeof dateString === 'string') {
return new Date(dateString);
}
else {
return dateString; //in case the argument is already an object
}
}
alert(MySQLToDate(a));
//iOS Output: Invalid Date
//Normal Output: Tue Mar 12 2019 12:30:03 GMT+0530 (India Standard Time)
It was working absolutely fine as expected until I tested it in iPad browsers.
It returns Invalid Date
in iOS. And of course, using the prototype function of Date()
like getDate()
, getMonth()
etc return Nan
.
So to overcome this situation, I researched and in one of the answers, I found out that passing the MySQL date directly into the JS Date function is a wrong practice. [Source]
Now my code looks like following:
var a = "2019-03-12 12:30:03"; //MySQL Date
function MySQLToDate(dateString) {
if (typeof dateString === 'string') {
return new Date(dateString.replace(" ","T"));
}
else {
return dateString; //in case the argument is already an object
}
}
alert(MySQLToDate(a));
//iOS Output: Tue Mar 12 2019 18:00:03 GMT+0530 (India Standard Time)
//Normal Output: Tue Mar 12 2019 12:30:03 GMT+0530 (India Standard Time)
This solution is not giving an Invalid Date Error but literally gives an Invalid Date.
I also tried splitting the MySQL date and passing year, month, date, hours, minutes, seconds into the Date()
but the time in the object is still wrong.
Your answers are most welcome.