Reputation: 95
I'm having trouble converting an example string: 'Sun Feb 02 19:12:44 +0000 2014'
to mysql dateTime format in javascript
any help would be greatly appreciated
Upvotes: 0
Views: 232
Reputation: 4218
try this:
var d = new Date('Sun Feb 02 19:12:44 +0000 2014');
var month = d.getMonth();
if(month < 10)
month = "0" + month;
var day = d.getDate();
if(day < 10)
day = "0" + day;
hour = d.getHours();
if(hour < 10)
hour = "0" + hour;
minute = d.getMinutes();
if(minute < 10)
minute = "0" + minute;
seconds = d.getSeconds();
if(seconds < 10)
seconds = "0" + seconds;
var mysqlDate = d.getFullYear() + "-" + month + "-" + day + " " + hour + ":" + minute + ":" + seconds;
Upvotes: 1
Reputation: 2241
You can convert date time to mysql format using this code:
var myDate = new Date('Sun Feb 02 19:12:44 +0000 2014'),
year = myDate.getFullYear(),
month = ('0' + (myDate.getMonth() + 1)).slice(-2),
day = ('0' + myDate.getDate()).slice(-2),
hour = ('0' + myDate.getHours()).slice(-2),
minute = ('0' + myDate.getMinutes()).slice(-2),
seconds = ('0' + myDate.getSeconds()).slice(-2),
mysqlDateTime = [year, month, day].join('-') + ' ' + [hour, minute, seconds].join(':');
However I would suggest to send it to backend as timestamp (+(new Date('Sun Feb 02 19:12:44 +0000 2014'))
) or formatted string (myDate.toISOString()
) and proceed with conversion there.
Upvotes: 1