Format a date time in Javascript in database format

Posted in Javascript -

In some admin forms for own purposes I needed to have a "now" function to put the current date and time into the text field using Javascript. For various reasons I preferred to do this on the client side with Javascript than on the server side with PHP. The date and time format needed to be in a database YYYY-MM-DD HH:MM:SS format so it could be directly inserted into the database.

Because the web forms were for my own purposes I don't need to bother validating them on the client side as I will always enter them correctly myself (and can suffer the consequences if I don't) so having the be populated in Javascript is perfectly acceptable for my purposes.

Refer to my previous Javascript post about padding a number to two digits with Javascript for the pad2() function used below.

The code for formatting the date and time into a database ready format in Javascript is as follows:

var dt = new Date();
var dtstring = dt.getFullYear()
    + '-' + pad2(dt.getMonth()+1)
    + '-' + pad2(dt.getDate())
    + ' ' + pad2(dt.getHours())
    + ':' + pad2(dt.getMinutes())
    + ':' + pad2(dt.getSeconds());

That will then put the current date and time into a database format e.g. "2009-04-24 07:00:00" which is the date and time this post is scheduled for publishing.

Note that getMonth() returns a number between 0 and 11 so 1 needs to be added to it. Although the day of the month function is labelled getDate() it does actually return the day of the month as a number between 1 and 31.

Related posts: