0

i need to send a datetime from javascript to sql in this folowing format: yyyy-mm-dd hh-mi-ss. After creating a variable

var n = new Date()

what should i do to fetch number in that format ? Thank you in advance !!

DaMatt91
  • 544
  • 1
  • 7
  • 18

3 Answers3

1

If you are working with dates in more than one place, I suggest you use moment.js. You can then do something like moment(n).format('YYYY-MM-DD HH-mm-ss') to achieve what you wanted.

luanped
  • 3,178
  • 2
  • 26
  • 40
1

Just use a slightly adapted version from MDN's Date.prototype.toISOString() polyfill:

if (!Date.prototype.toSQLString) {
    (function() {

        function pad(number) {
            if (number < 10) {
                return '0' + number;
            }
            return number;
        }

        Date.prototype.toSQLOString = function() {
            return this.getUTCFullYear() +
                '-' + pad(this.getUTCMonth() + 1) +
                '-' + pad(this.getUTCDate()) +
                ' ' + pad(this.getUTCHours()) +
                '-' + pad(this.getUTCMinutes()) +
                '-' + pad(this.getUTCSeconds());
        };
    }());
}

document.write((new Date()).toSQLOString());
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
  • Of course, this only works if you want a UTC-based result. You would need to modify it to use different functions if you want local time. – Matt Johnson-Pint Dec 02 '15 at 19:26
-2

Steven Levithan wrote a really nice dateFormat function.

 var sqlDateStr = new Date().format("yyyy-mm-dd hh-MM-ss");
 console.log(sqlDateStr)

http://jsfiddle.net/gbs93qwb/

jonfriesen
  • 625
  • 6
  • 19