197

Does anyone know how to convert JS dateTime to MySQL datetime? Also is there a way to add a specific number of minutes to JS datetime and then pass it to MySQL datetime?

locoboy
  • 38,002
  • 70
  • 184
  • 260

26 Answers26

426
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 , consider https://github.com/taylorhakes/fecha

require('fecha').format('YYYY-MM-DD HH:mm:ss')
Gajus
  • 69,002
  • 70
  • 275
  • 438
  • 1
    You have an extra opening parenthesis before date.getUTCDate, and yes this is better. – Adam Lockhart Apr 09 '13 at 16:42
  • Than an implementation suggest by you. – Gajus Oct 29 '13 at 15:53
  • I thought that's what you meant. :) Can you explain in what way you think this is nicer? – kojiro Nov 20 '13 at 14:36
  • @kojiro No unnecessary if conditionals, no redundant padding function, better readability. At the end, it is a matter of personal taste. – Gajus Nov 20 '13 at 14:43
  • The `toISOString` approach is better for modern browsers. (It's supported in IE9 and above.) FWIW, the `toISOString` polyfill described by MDN has a padding function similar to mine. :P – kojiro Dec 18 '13 at 16:16
  • 39
    this will give problem due to timezone – Mr Coder Mar 20 '14 at 03:11
  • 5
    It throws away the timezone setting, how to keep it? – shapeare Nov 17 '14 at 17:25
  • Don't use the "UTC" version of the function. The ISO version is not going to work. – Gajus Nov 17 '14 at 17:49
  • Thanks @Gajus, I was able to use the same idea the other way around, first `.slice(0,19)` then `.replace(' ','T')` in order to convert a MySQL date to a date suitable for Javascript. Cool. – Phil Ryan Mar 04 '15 at 02:41
  • `toISOString` support: http://kangax.github.io/compat-table/es5/#Date.prototype.toISOString – Justin Jun 29 '15 at 17:39
  • 2
    combo it up with this to take care of the timezone: http://stackoverflow.com/questions/11887934/check-if-daylight-saving-time-is-in-effect-and-if-it-is-for-how-many-hours – chiliNUT Jul 06 '15 at 23:29
  • Just use moment, trust me. (I'm on the internet so I'm right) – txulu Jul 15 '15 at 16:19
  • The first `0` of `('00' + date....` will never be included in output since `(date.getAnything().length > 0)` is always `true` ;) – Martin Schneider Nov 22 '16 at 13:06
  • @MA-Maddin Its there simply for code consistency. Its easier to scan code when some logic is applied consistently. – Gajus Nov 22 '16 at 13:19
  • @Gajus: replacing all `00` by `0` is still code consistent?! :) – Martin Schneider Nov 22 '16 at 14:30
  • I am probably not understanding your argument. I am referring to the visual appearance of the code. – Gajus Nov 22 '16 at 17:43
  • Please add something to highlight even shorter part I just missed that part in a hurry.And got the answer from https://stackoverflow.com/a/44831930/6517383 same as yours – Black Mamba Jul 26 '17 at 06:47
  • @chiliNUT could you give an example of "combo it up with this to take care of the timezone" I see the slack post on how daylight savings etc, but how would you wrap that into the ISO solution here. I'm not following. – user1819575 Jun 28 '18 at 04:19
  • Incase anyone was interested... Testing this for Daylight savings it seemed to work just fine let aa = new Date('March 10, 2018 00:00:00'); let bb = new Date('March 12, 2018 00:00:00'); aa.toISOString().slice(0, 19).replace('T', ' '); "2018-03-10 07:00:00" bb.toISOString().slice(0, 19).replace('T', ' '); "2018-03-12 06:00:00" – user1819575 Jun 28 '18 at 04:42
  • @user1819575 while the linked question is specifically about DST, it also contains good bakground on getting the timezone offset in general. So, assuming your mysql datetime field is set to UTC timezone, I meant that you take your javascript Date instance, then find the timezone offset and add it (and optionally factor in DST), which converts your date to UTC, and then call isostring on that to get a mysql formatted timestamp in UTC – chiliNUT Jun 28 '18 at 06:49
  • 8
    Full workaround with timezone oneliner!! `var d = new Date(); d.toISOString().split('T')[0]+' '+d.toTimeString().split(' ')[0];` – Paulo Roberto Rosa Sep 28 '18 at 19:20
  • this gives the correct one. https://stackoverflow.com/questions/5129624/convert-js-date-time-to-mysql-datetime/60002673#60002673 – Nisuga Jayawardana Jan 31 '20 at 11:12
  • Beware, the solution from @PauloRobertoRosa in the comment above doesn't work properly when the timezone day is different than UTC! See [this answer](https://stackoverflow.com/a/57390893/1317406) for more information – Samuli Asmala Dec 13 '21 at 14:56
  • I recently had to fix a bug because I didn't read the warnings about how this will cause issues if your timezone is not UTC, learn from me and use `moment` instead. – Jorche Jan 20 '22 at 02:30
133

I think the solution can be less clunky by using method toISOString(), it has a wide browser compatibility.

So your expression will be a one-liner:

new Date().toISOString().slice(0, 19).replace('T', ' ');

The generated output:

"2017-06-29 17:54:04"

Farside
  • 9,923
  • 4
  • 47
  • 60
  • 3
    Works brilliantly! `new Date(1091040026000).toISOString().slice(0, 19).replace('T', ' ');` – John Aug 26 '17 at 18:27
  • 6
    Great, only one issue here: the more clunky methods will be getting the hour, day, month (even year) **after** application of the js `Date`'s *time zone offset*. Whereas yours returns the underlying UTC time in MySQL DATETIME format. In most cases storing the UTC may be better, and in either case your data table should probably give location info in one field. Alternatively, to convert to local time is pretty easy: use `... - Date.getTimezoneOffset() * 60 * 1000` (NB also adjusts for Daylight Saving Time where applicable). – mike rodent Aug 28 '17 at 17:38
  • do you need the (dot)slice part? – edwardsmarkf Nov 20 '22 at 01:10
96

While JS does possess enough basic tools to do this, it's pretty clunky.

/**
 * You first need to create a formatting function to pad numbers to two digits…
 **/
function twoDigits(d) {
    if(0 <= d && d < 10) return "0" + d.toString();
    if(-10 < d && d < 0) return "-0" + (-1*d).toString();
    return d.toString();
}

/**
 * …and then create the method to output the date string as desired.
 * Some people hate using prototypes this way, but if you are going
 * to apply this to more than one Date object, having it as a prototype
 * makes sense.
 **/
Date.prototype.toMysqlFormat = function() {
    return this.getUTCFullYear() + "-" + twoDigits(1 + this.getUTCMonth()) + "-" + twoDigits(this.getUTCDate()) + " " + twoDigits(this.getUTCHours()) + ":" + twoDigits(this.getUTCMinutes()) + ":" + twoDigits(this.getUTCSeconds());
};
kojiro
  • 74,557
  • 19
  • 143
  • 201
  • How do you call a function like this with a variable? – Catfish Mar 12 '13 at 04:50
  • 1
    @Catfish You mean with a specific date? You use a `Date` object. `new Date().toMysqlFormat()` or `new Date(2014,12,14).toMysqlFormat()` or whatever. – kojiro Mar 12 '13 at 12:36
  • 22
    This answer had its day while JavaScript was old and clunky. If you target a modern browser, I recommend [Gajus' `toISOString` approach](http://stackoverflow.com/a/11150727/418413). – kojiro Dec 18 '13 at 16:18
22

JS time value for MySQL

const DATE_FORMATER = require( 'dateformat' );
var datetime = DATE_FORMATER( new Date(), "yyyy-mm-dd HH:MM:ss" );

OR

const MOMENT = require( 'moment' );
let datetime = MOMENT().format( 'YYYY-MM-DD  HH:mm:ss.000' );

you can send this in params its will work.

M. Hamza Rajput
  • 7,810
  • 2
  • 41
  • 36
  • 4
    toLocaleString() depends on what the locale is. It may be the same as mysql in some places, but it really isn't a good approach generally – havlock Sep 26 '20 at 16:12
  • But, a slight variation of localeString can be helpful - `${d.toLocaleDateString("EN-CA")} ${d.toLocaleTimeString("EN-GB")}` – havlock Jan 28 '23 at 09:58
  • Incorrect datetime value: '4/7/2023, 11:09:53 AM' Doesn't work. I figured it wouldn't, but I was curious because 19 people updooted you. – Sean Patnode Apr 08 '23 at 13:45
  • you can use dateformate or moment library. i personally use moment – M. Hamza Rajput Apr 10 '23 at 07:56
14

For arbitrary date string,

// Your default date object  
var starttime = new Date();
// Get the iso time (GMT 0 == UTC 0)
var isotime = new Date((new Date(starttime)).toISOString() );
// getTime() is the unix time value, in milliseconds.
// getTimezoneOffset() is UTC time and local time in minutes.
// 60000 = 60*1000 converts getTimezoneOffset() from minutes to milliseconds. 
var fixedtime = new Date(isotime.getTime()-(starttime.getTimezoneOffset()*60000));
// toISOString() is always 24 characters long: YYYY-MM-DDTHH:mm:ss.sssZ.
// .slice(0, 19) removes the last 5 chars, ".sssZ",which is (UTC offset).
// .replace('T', ' ') removes the pad between the date and time.
var formatedMysqlString = fixedtime.toISOString().slice(0, 19).replace('T', ' ');
console.log( formatedMysqlString );

Or a single line solution,

var formatedMysqlString = (new Date ((new Date((new Date(new Date())).toISOString() )).getTime() - ((new Date()).getTimezoneOffset()*60000))).toISOString().slice(0, 19).replace('T', ' ');
console.log( formatedMysqlString );

This solution also works for Node.js when using Timestamp in mysql.

@Gajus Kuizinas's first answer seems to modify mozilla's toISOString prototype

Paul Totzke
  • 1,470
  • 17
  • 33
9
new Date().toISOString().slice(0, 10)+" "+new Date().toLocaleTimeString('en-GB');
Abhinav Kinagi
  • 3,653
  • 2
  • 27
  • 43
Nirbhay Kumar
  • 91
  • 1
  • 1
8

The easiest correct way to convert JS Date to SQL datetime format that occur to me is this one. It correctly handles timezone offset.

const toSqlDatetime = (inputDate) => {
    const date = new Date(inputDate)
    const dateWithOffest = new Date(date.getTime() - (date.getTimezoneOffset() * 60000))
    return dateWithOffest
        .toISOString()
        .slice(0, 19)
        .replace('T', ' ')
}

toSqlDatetime(new Date()) // 2019-08-07 11:58:57
toSqlDatetime(new Date('2016-6-23 1:54:16')) // 2016-06-23 01:54:16

Beware that @Paulo Roberto answer will produce incorrect results at the turn on new day (i can't leave comments). For example:

var d = new Date('2016-6-23 1:54:16'),
    finalDate = d.toISOString().split('T')[0]+' '+d.toTimeString().split(' ')[0];
console.log(finalDate); // 2016-06-22 01:54:16 

We've got 22 June instead of 23!

5

This is by far the easiest way I can think of

new Date().toISOString().slice(0, 19).replace("T", " ")
4

The venerable DateJS library has a formatting routine (it overrides ".toString()"). You could also do one yourself pretty easily because the "Date" methods give you all the numbers you need.

Pointy
  • 405,095
  • 59
  • 585
  • 614
4

The short version:

// JavaScript timestamps need to be converted to UTC time to match MySQL

// MySQL formatted UTC timestamp +30 minutes
let d = new Date()
let mySqlTimestamp = new Date(
  d.getFullYear(),
  d.getMonth(),
  d.getDate(),
  d.getHours(),
  (d.getMinutes() + 30), // add 30 minutes
  d.getSeconds(),
  d.getMilliseconds()
).toISOString().slice(0, 19).replace('T', ' ')

console.log("MySQL formatted UTC timestamp: " + mySqlTimestamp)

UTC time is generally the best option for storing timestamps in MySQL. If you don't have root access, then run set time_zone = '+00:00' at the start of your connection.

Display a timestamp in a specific time zone in MySQL with the method convert_tz.

select convert_tz(now(), 'SYSTEM', 'America/Los_Angeles');

JavaScript timestamps are based on your device's clock and include the time zone. Before sending any timestamps generated from JavaScript, you should convert them to UTC time. JavaScript has a method called toISOString() which formats a JavaScript timestamp to look similar to MySQL timestamp and converts the timestamp to UTC time. The final cleanup takes place with slice and replace.

let timestmap = new Date()
timestmap.toISOString().slice(0, 19).replace('T', ' ')

Long version to show what is happening:

// JavaScript timestamps need to be converted to UTC time to match MySQL

// local timezone provided by user's device
let d = new Date()
console.log("JavaScript timestamp: " + d.toLocaleString())

// add 30 minutes
let add30Minutes = new Date(
  d.getFullYear(),
  d.getMonth(),
  d.getDate(),
  d.getHours(),
  (d.getMinutes() + 30), // add 30 minutes
  d.getSeconds(),
  d.getMilliseconds()
)
console.log("Add 30 mins: " + add30Minutes.toLocaleString())

// ISO formatted UTC timestamp
// timezone is always zero UTC offset, as denoted by the suffix "Z"
let isoString = add30Minutes.toISOString()
console.log("ISO formatted UTC timestamp: " + isoString)

// MySQL formatted UTC timestamp: YYYY-MM-DD HH:MM:SS
let mySqlTimestamp = isoString.slice(0, 19).replace('T', ' ')
console.log("MySQL formatted UTC timestamp: " + mySqlTimestamp)
Xman
  • 41
  • 2
3

Full workaround (to mantain the timezone) using @Gajus answer concept:

var d = new Date(),
    finalDate = d.toISOString().split('T')[0]+' '+d.toTimeString().split(' ')[0];
console.log(finalDate); //2018-09-28 16:19:34 --example output
Paulo Roberto Rosa
  • 3,071
  • 5
  • 28
  • 53
3

I am surprised that no one mention the Swedish date time format for javascript yet.
the BCP 47 language tag for the Swedish language is sv-SE that you can use for the new Date "locale" parameter.
I am not saying it is a good practice, but it works.

console.log(new Date().toLocaleString([['sv-SE']])) //2022-09-10 17:02:39
faizz
  • 31
  • 4
2

I have given simple JavaScript date format examples please check the bellow code

var data = new Date($.now()); // without jquery remove this $.now()
console.log(data)// Thu Jun 23 2016 15:48:24 GMT+0530 (IST)

var d = new Date,
    dformat = [d.getFullYear() ,d.getMonth()+1,
               d.getDate()
               ].join('-')+' '+
              [d.getHours(),
               d.getMinutes(),
               d.getSeconds()].join(':');

console.log(dformat) //2016-6-23 15:54:16

Using momentjs

var date = moment().format('YYYY-MM-DD H:mm:ss');

console.log(date) // 2016-06-23 15:59:08

Example please check https://jsfiddle.net/sjy3vjwm/2/

Raja Rama Mohan Thavalam
  • 8,131
  • 2
  • 31
  • 30
  • I just tried your first code with vanilla javascript and it gives me this result: 2018-4-20 15:11:23. You are not padding the numbers with a leading "0". Also, I don't know about momentjs but don't you have to put "HH" for hour so that it pads it? Maybe that's why you got down voted? (itwasntme) – Alex Apr 20 '18 at 20:16
2
var _t = new Date();

if you want UTC format simply

_t.toLocaleString('indian', { timeZone: 'UTC' }).replace(/(\w+)\/(\w+)\/(\w+), (\w+)/, '$3-$2-$1 $4');

or

_t.toISOString().slice(0, 19).replace('T', ' ');

and if want in specific timezone then

_t.toLocaleString('indian', { timeZone: 'asia/kolkata' }).replace(/(\w+)\/(\w+)\/(\w+), (\w+)/, '$3-$2-$1 $4');
Suraj Inamdar
  • 181
  • 1
  • 1
2

Using toJSON() date function as below:

var sqlDatetime = new Date(new Date().getTime() - new Date().getTimezoneOffset() * 60 * 1000).toJSON().slice(0, 19).replace('T', ' ');
console.log(sqlDatetime);
Abhinav Kinagi
  • 3,653
  • 2
  • 27
  • 43
2

Datetime in a different time zone

This uses @Gayus solution using the format outputted from toISOString() but it adjusts the minutes to account for the time zone. Final format: 2022-03-01 13:32:51

let ts = new Date();
ts.setMinutes(ts.getMinutes() - ts.getTimezoneOffset());
console.log(ts.toISOString().slice(0, 19).replace('T', ' '));
Sofía
  • 784
  • 10
  • 24
1

A simple solution is send a timestamp to MySQL and let it do the conversion. Javascript uses timestamps in milliseconds whereas MySQL expects them to be in seconds - so a division by 1000 is needed:

// Current date / time as a timestamp:
let jsTimestamp = Date.now();

// **OR** a specific date / time as a timestamp:
jsTimestamp = new Date("2020-11-17 16:34:59").getTime();

// Adding 30 minutes (to answer the second part of the question):
jsTimestamp += 30 * 1000;

// Example query converting Javascript timestamp into a MySQL date
let sql = 'SELECT FROM_UNIXTIME(' + jsTimestamp + ' / 1000) AS mysql_date_time';
Steve Chambers
  • 37,270
  • 24
  • 156
  • 208
1

I needed a function to return the sql timestamp format in javascript form a selective timezone

<script>
console.log(getTimestamp("Europe/Amsterdam")); // Europe/Amsterdam
console.log(getTimestamp()); // UTC

function getTimestamp(timezone) {
  if (timezone) { 
  var dateObject = new Date().toLocaleString("nl-NL", { // it will parse with the timeZone element, not this one
    timeZone: timezone, // timezone eg "Europe/Amsterdam" or "UTC"
    month: "2-digit",
    day: "2-digit",
    year: "numeric",

    hour: "2-digit",
    minute: "2-digit",
    second: "2-digit",
  });

  let [dateRaw, timeRaw] = dateObject.split(" ");
  let [day, month, year] = dateRaw.split("-");
  var timestamp = year + "-" + month + "-" + day + " " + timeRaw;
  }else{
  // UTC from @Gajus, 95% faster then the above
  timestamp = new Date().toISOString().slice(0, 19).replace("T", " ");
  }
  return timestamp; // YYYY-MM-DD HH:MI:SS
}
</script>
Kima
  • 119
  • 1
  • 4
1

If you are using Date-fns then the functionality can be achived easily using format function.

const format = require("date-fns/format");
const date = new Date();

const formattedDate = format(date, "yyyy-MM-dd HH:mm:ss")
NS23
  • 684
  • 5
  • 14
1

This is the easiest way -

new Date().toISOString().slice(0, 19).replace("T", " ")

Tzachi Elrom
  • 385
  • 1
  • 2
  • 19
0

I'm using this long time and it's very helpful for me, use as you like

Date.prototype.date=function() {
    return this.getFullYear()+'-'+String(this.getMonth()+1).padStart(2, '0')+'-'+String(this.getDate()).padStart(2, '0')
}

Date.prototype.time=function() {
    return String(this.getHours()).padStart(2, '0')+':'+String(this.getMinutes()).padStart(2, '0')+':'+String(this.getSeconds()).padStart(2, '0')
}

Date.prototype.dateTime=function() {
    return this.getFullYear()+'-'+String(this.getMonth()+1).padStart(2, '0')+'-'+String(this.getDate()).padStart(2, '0')+' '+String(this.getHours()).padStart(2, '0')+':'+String(this.getMinutes()).padStart(2, '0')+':'+String(this.getSeconds()).padStart(2, '0')
}

Date.prototype.addTime=function(time) {
    var time=time.split(":")
    var rd=new Date(this.setHours(this.getHours()+parseInt(time[0])))
    rd=new Date(rd.setMinutes(rd.getMinutes()+parseInt(time[1])))
    return new Date(rd.setSeconds(rd.getSeconds()+parseInt(time[2])))
}

Date.prototype.addDate=function(time) {
    var time=time.split("-")
    var rd=new Date(this.setFullYear(this.getFullYear()+parseInt(time[0])))
    rd=new Date(rd.setMonth(rd.getMonth()+parseInt(time[1])))
    return new Date(rd.setDate(rd.getDate()+parseInt(time[2])))
}

Date.prototype.subDate=function(time) {
    var time=time.split("-")
    var rd=new Date(this.setFullYear(this.getFullYear()-parseInt(time[0])))
    rd=new Date(rd.setMonth(rd.getMonth()-parseInt(time[1])))
    return new Date(rd.setDate(rd.getDate()-parseInt(time[2])))
}

and then just:

new Date().date()

which returns current date in 'MySQL format'

for add time is

new Date().addTime('0:30:0')

which will add 30 minutes.... and so on

0

Solution built on the basis of other answers, while maintaining the timezone and leading zeros:

var d = new Date;

var date = [
    d.getFullYear(),
    ('00' + d.getMonth() + 1).slice(-2),
    ('00' + d.getDate() + 1).slice(-2)
].join('-');

var time = [
    ('00' + d.getHours()).slice(-2),
    ('00' + d.getMinutes()).slice(-2),
    ('00' + d.getSeconds()).slice(-2)
].join(':');

var dateTime = date + ' ' + time;
console.log(dateTime) // 2021-01-41 13:06:01
Serhii Vasko
  • 383
  • 4
  • 11
0

Simple: just Replace the T. Format that I have from my <input class="form-control" type="datetime-local" is : "2021-02-10T18:18"

So just replace the T, and it would look like this: "2021-02-10 18:18" SQL will eat that.

Here is my function:

var CreatedTime = document.getElementById("example-datetime-local-input").value;

var newTime = CreatedTime.replace("T", " ");

Reference: https://www.tutorialrepublic.com/faq/how-to-replace-character-inside-a-string-in-javascript.php#:~:text=Answer%3A%20Use%20the%20JavaScript%20replace,the%20global%20(%20g%20)%20modifier.

https://www.tutorialrepublic.com/codelab.php?topic=faq&file=javascript-replace-character-in-a-string

MikeRyz
  • 209
  • 1
  • 3
  • 18
0

What about this one taking account the timezone offset?

const getTimestamp = (date = false) => {
  const d = ! date ? new Date() : new Date(date);

  return new Date(d - d.getTimezoneOffset() * 60 * 1000).toJSON().replace('T', ' ').split('.')[0];
}

console.log(getTimestamp());
console.log(getTimestamp('2016-6-23 1:54:16'));
Puerto AGP
  • 393
  • 5
  • 11
0

const dateToSqlDate = (date) => date.toISOString().slice(0, -5).replace('T', ' ')

console.log(dateToSqlDate(new Date()))
Dominic
  • 62,658
  • 20
  • 139
  • 163
0

That works fine for me:

function DateToSql(d: Date): string {
    let dt: Date = new Date(d.getTime());
    dt.setTime(dt.getTime() - dt.getTimezoneOffset() * 60000);
    return dt.toISOString().slice(0, 19).replace('T', ' ');
}