[javascript] Javascript: output current datetime in YYYY/mm/dd hh:m:sec format

I need to output the current UTC datetime as a string with the following format:
YYYY/mm/dd hh:m:sec

How do I achieve that with Javascript?

This question is related to javascript datetime

The answer is


Alternative to answer of @JosephMarikle If you do not want to figth against timezone UTC etc:

var dateString =
        ("0" + date.getUTCDate()).slice(-2) + "/" +
        ("0" + (date.getUTCMonth()+1)).slice(-2) + "/" +
        date.getUTCFullYear() + " " +
        //return HH:MM:SS with localtime without surprises
        date.toLocaleTimeString()
    console.log(fechaHoraActualCadena);

With jQuery date format :

$.format.date(new Date(), 'yyyy/MM/dd HH:mm:ss');

https://github.com/phstc/jquery-dateFormat

Enjoy


Not tested, but something like this:

var now = new Date();
var str = now.getUTCFullYear().toString() + "/" +
          (now.getUTCMonth() + 1).toString() +
          "/" + now.getUTCDate() + " " + now.getUTCHours() +
          ":" + now.getUTCMinutes() + ":" + now.getUTCSeconds();

Of course, you'll need to pad the hours, minutes, and seconds to two digits or you'll sometimes get weird looking times like "2011/12/2 19:2:8."


I wrote a simple library for manipulating the JavaScript date object. You can try this:

var dateString = timeSolver.getString(new Date(), "YYYY/MM/DD HH:MM:SS.SSS")

Library here: https://github.com/sean1093/timeSolver


Posting another script solution DateX (author) for anyone interested

DateX does NOT wrap the original Date object, but instead offers an identical interface with additional methods to format, localise, parse, diff and validate dates easily. So one can just do new DateX(..) instead of new Date(..) or use the lib as date utilities or even as wrapper or replacement around Date class.

The date format used is identical to php date format.

c-like format is also supported (although not fully)

for the example posted (YYYY/mm/dd hh:m:sec) the format to use would be Y/m/d H:i:s eg

var formatted_date = new DateX().format('Y/m/d H:i:s');

or

var formatted_now_date_gmt = new DateX(DateX.UTC()).format('Y/m/d H:i:s');

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/UTC


No library, one line, properly padded

const str = (new Date()).toISOString().slice(0, 19).replace(/-/g, "/").replace("T", " ");

It uses the built-in function Date.toISOString(), chops off the ms, replaces the hyphens with slashes, and replaces the T with a space to go from say '2019-01-05T09:01:07.123' to '2019/01/05 09:01:07'.

Local time instead of UTC

const now = new Date();
const offsetMs = now.getTimezoneOffset() * 60 * 1000;
const dateLocal = new Date(now.getTime() - offsetMs);
const str = dateLocal.toISOString().slice(0, 19).replace(/-/g, "/").replace("T", " ");