Convert JS date time to MySQL datetime
var date;
date = new Date();
date = date.getUTCFullYear() + '-' +
('00' + (date.getUTCMonth()+1)).slice(-2) + '-' +
('00' + date.getUTCDate()).slice(-2) + ' ' +
('00' + date.getUTCHours()).slice(-2) + ':' +
('00' + date.getUTCMinutes()).slice(-2) + ':' +
('00' + date.getUTCSeconds()).slice(-2);
console.log(date);
or even shorter:
new Date().toISOString().slice(0, 19).replace('T', ' ');
Output:
2012-06-22 05:40:06
For more advanced use cases, including controlling the timezone, consider using http://momentjs.com/:
require('moment')().format('YYYY-MM-DD HH:mm:ss');
For a lightweight alternative to momentjs, consider https://github.com/taylorhakes/fecha
require('fecha').format('YYYY-MM-DD HH:mm:ss')
How to convert a Timestamp into MySQL DateTime in JavaScript?
You can pass the Date
object of JavaScript directly to MySQL. And MySQL will automatically generate the DateTime
format from that Date
object.
const date = new Date(1631514003973);
How to convert JS date time to Local MySQL datetime?
If you just need to add 7 hours here is an example:
<html>
<head> <title>Web Page Design</title> <script> var now = new Date(); now.setHours(now.getHours() + 7); document.writeln(now.toISOString().slice(0, 19).replace('T', ' '));
</script> </head>
<body><br>Current Date is displayed above...</body>
</html>`
Convert Javascript DateTime LocalTime To Mysql Datetime
const date1 = new Date(1658483664000);
var date =moment(date1 ).format('MM-DD-YYYY HH:mm:ss');
to use this code you need to include moment.js in your project
https://momentjs.com
Convert MySql DateTime stamp into JavaScript's Date format
Some of the answers given here are either overcomplicated or just will not work (at least, not in all browsers). If you take a step back, you can see that the MySQL timestamp has each component of time in the same order as the arguments required by the Date()
constructor.
All that's needed is a very simple split on the string:
// Split timestamp into [ Y, M, D, h, m, s ]
var t = "2010-06-09 13:12:01".split(/[- :]/);
// Apply each element to the Date function
var d = new Date(Date.UTC(t[0], t[1]-1, t[2], t[3], t[4], t[5]));
console.log(d);
// -> Wed Jun 09 2010 14:12:01 GMT+0100 (BST)
Fair warning: this assumes that your MySQL server is outputting UTC dates (which is the default, and recommended if there is no timezone component of the string).
Convert Javascript time to MySQL format using PHP
Since your date string already contains the time zone, you don't need to do anything special:
$when = new DateTime('Sun Jul 13 2014 07:00:00 GMT+0200 (EET)');
echo $when->format('Y-m-d H:i:s');
As helpfully noted in comments, this string actually contains two bits of time zone information, UTC + 2 and EET (Eastern European Time), and PHP is basically ignoring the second one. It's spotted better in this example:
var_dump(new DateTime('Sun Jul 13 2014 07:00:00 GMT+0200 (EET)'), DateTime::getLastErrors());
var_dump(new DateTime('Sun Jul 13 2014 07:00:00 GMT+0200'), DateTime::getLastErrors());
var_dump(new DateTime('Sun Jul 13 2014 07:00:00 (EET)'), DateTime::getLastErrors());
object(DateTime)#1 (3) {
["date"]=>
string(26) "2014-07-13 07:00:00.000000"
["timezone_type"]=>
int(1)
["timezone"]=>
string(6) "+02:00"
}
array(4) {
["warning_count"]=>
int(1)
["warnings"]=>
array(1) {
[34]=>
string(29) "Double timezone specification"
}
["error_count"]=>
int(0)
["errors"]=>
array(0) {
}
}
object(DateTime)#1 (3) {
["date"]=>
string(26) "2014-07-13 07:00:00.000000"
["timezone_type"]=>
int(1)
["timezone"]=>
string(6) "+02:00"
}
array(4) {
["warning_count"]=>
int(0)
["warnings"]=>
array(0) {
}
["error_count"]=>
int(0)
["errors"]=>
array(0) {
}
}
object(DateTime)#1 (3) {
["date"]=>
string(26) "2014-07-13 07:00:00.000000"
["timezone_type"]=>
int(2)
["timezone"]=>
string(3) "EET"
}
array(4) {
["warning_count"]=>
int(0)
["warnings"]=>
array(0) {
}
["error_count"]=>
int(0)
["errors"]=>
array(0) {
}
}
We in fact need to strip one of them, e.g.:
$js_date_string = 'Sun Jul 13 2014 07:00:00 GMT+0200 (EET)';
// Regular expression is shown for illustration purposes, it's probably wrong!
$tmp_date_string = preg_replace('/ GMT\+\d{4}/ui', '', $js_date_string);
$when = new DateTime($tmp_date_string);
var_dump($when, DateTime::getLastErrors());
echo $when->format('Y-m-d H:i:s');
object(DateTime)#1 (3) {
["date"]=>
string(26) "2014-07-13 07:00:00.000000"
["timezone_type"]=>
int(2)
["timezone"]=>
string(3) "EET"
}
array(4) {
["warning_count"]=>
int(0)
["warnings"]=>
array(0) {
}
["error_count"]=>
int(0)
["errors"]=>
array(0) {
}
}
2014-07-13 07:00:00
Convert JavaScript to date object to MySQL date format (YYYY-MM-DD)
Update: Here in 2021, Date.js hasn't been maintained in years and is not recommended, and Moment.js is in "maintenance only" mode. We have the built-in Intl.DateTimeFormat
, Intl.RelativeTimeFormat
, and (soon) Temporal
instead, probably best to use those. Some useful links are linked from Moment's page on entering maintenance mode.
Old Answer:
Probably best to use a library like Date.js (although that hasn't been maintained in years) or Moment.js.
But to do it manually, you can use Date#getFullYear()
, Date#getMonth()
(it starts with 0 = January, so you probably want + 1), and Date#getDate()
(day of month). Just pad out the month and day to two characters, e.g.:
(function() {
Date.prototype.toYMD = Date_toYMD;
function Date_toYMD() {
var year, month, day;
year = String(this.getFullYear());
month = String(this.getMonth() + 1);
if (month.length == 1) {
month = "0" + month;
}
day = String(this.getDate());
if (day.length == 1) {
day = "0" + day;
}
return year + "-" + month + "-" + day;
}
})();
Usage:
var dt = new Date();
var str = dt.toYMD();
Note that the function has a name, which is useful for debugging purposes, but because of the anonymous scoping function there's no pollution of the global namespace.
That uses local time; for UTC, just use the UTC versions (getUTCFullYear
, etc.).
Caveat: I just threw that out, it's completely untested.
Javascript date to sql date object
Have you tried the solutions presented here:
Convert JS date time to MySQL datetime
The title should be called
"Convert JS date to SQL DateTime"
I happened to need to do the same thing as you just now and I ran across this after your question.
This is from the other post by Gajus Kuizinas for those who want the answers on this page:
var pad = function(num) { return ('00'+num).slice(-2) };
var date;
date = new Date();
date = date.getUTCFullYear() + '-' +
pad(date.getUTCMonth() + 1) + '-' +
pad(date.getUTCDate()) + ' ' +
pad(date.getUTCHours()) + ':' +
pad(date.getUTCMinutes()) + ':' +
pad(date.getUTCSeconds());
or
new Date().toISOString().slice(0, 19).replace('T', ' ');
The first one worked for me. I had a reference problem with the toISOString as well although I would prefer the one liner. Can anyone clarify how to use it and know the limitations on where one can reference it?
Good luck!
Related Topics
How to Make API Call with Hooks in React
How to Get Class Object's Name as a String in JavaScript
Split String Only on First Instance of Specified Character
JavaScript .Replace Command Replace Page Text
Sanitizing User Input Before Adding It to the Dom in JavaScript
Is There a Sleep Function in JavaScript
Convert Js Date Time to MySQL Datetime
Jquery Difference Between Change and Click Event of Checkbox
How to Sort an Array Without Mutating the Original Array
How to Remove Documents Using Node.Js Mongoose
How to Break Nested Loops in JavaScript
Are Dashes Allowed in JavaScript Property Names
How to Copy JavaScript Object to New Variable Not by Reference
How to Set a Js Object Property Name from a Variable
Is Onload Equal to Readystate==4 in Xmlhttprequest
Truncate (Not Round Off) Decimal Numbers in JavaScript
How to Implement Cross Domain Url Access from an Iframe Using JavaScript