MySQL NOW() in JavaScript (UTC & Local)


Read {count} times since 2020

If you know MySQL, you will certainly know the NOW() function that outputs the current date and time with the timezone of the MySQL server. For easy use and compatibility, we use UTC time zone for storing time in database. If you are running a web app that comply with MySQL, then you need the date function as same as the NOW().

So, I will give you a small function that return the same value as MySQL’s NOW() function in both UTC and local time. There are 2 versions of this function, one little big and the other very short (1 line of code). The shorter one is supported by modern browsers and the other is supported by all browsers.

Longer Function

Common Function

In both cases (UTC, Local) you need a common function that corrects a single digit value to 2 digit value. Here is the function :

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();
}

UTC

This function gives the current UTC date time :

function NOW(){
 t=new Date();
 return t.getUTCFullYear() + "-" + twoDigits(1 + t.getUTCMonth()) + "-" + twoDigits(t.getUTCDate()) + " " + twoDigits(t.getUTCHours()) + ":" + twoDigits(t.getUTCMinutes()) + ":" + twoDigits(t.getUTCSeconds());
}

Note that we use the twoDigits function in the above code.

Local

Get the current local time of the client’s browser / system :

function NOW(){
 t=new Date();
 return t.getFullYear() + "-" + twoDigits(1 + t.getMonth()) + "-" + twoDigits(t.getDate()) + " " + twoDigits(t.getHours()) + ":" + twoDigits(t.getMinutes()) + ":" + twoDigits(t.getSeconds());
}

All we have to do is replace all UTC word from the UTC NOW() code and you’ll get the local date time code.

Easy, Shorter Function

There’s another easy approach to the NOW() function. It’s by using .toISOString(). This supports all modern browsers.

UTC

function NOW(){
 return new Date().toISOString().slice(0, 19).replace('T', ' ');
}

Local

function NOW(){
 return new Date(new Date()+" UTC").toISOString().slice(0, 19).replace('T', ' ');
}

Usage

The usage is same in both cases :

console.log(NOW())

If you used the UTC version of NOW(), then it will print something like :

2014-04-04 06:50:44

In the local case, it would be :

2014-04-04 12:20:44

You can include the date time in a variable too :

var curDateTime = NOW();

Happy coding.

Show Comments