70

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?

MarredCheese
  • 9,495
  • 5
  • 59
  • 63
sarsnake
  • 23,178
  • 58
  • 166
  • 281
  • By "capture" do you mean that you want to parse a string that is that format into a Date object or that you have a Date object and you want to output it as a string in that format? – dgvid Dec 02 '11 at 21:33
  • no, I mean I need to do something like var now = new Date(); it does work. But I need to convert it to GMT and format it as specified above – sarsnake Dec 02 '11 at 21:34
  • Please check this link - http://stackoverflow.com/questions/489581/getting-the-current-gmt-world-time – Samik Chattopadhyay Dec 02 '11 at 21:36
  • 1
    holly......that's a lot of work. what about toGMTString()? Not good? – sarsnake Dec 02 '11 at 21:39
  • @sarsnake JavaScript Dates only know local and UTC, not GMT -- [`toUTCString`](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date/toUTCString). – Jonathan Lonowski Dec 02 '11 at 21:41
  • oh gotcha. I think I need UTC – sarsnake Dec 02 '11 at 21:42
  • @Jonathan You can figure out GMT time by using getTimezoneOffset() and compensating... – John Strickler Dec 02 '11 at 21:53
  • 1
    @JohnStrickler That'll result in UTC as well. But, my point was that JavaScript/ECMAScript Dates simply don't recognize it as GMT, which is why [`toGMTString`](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date/toGMTString) has been deprecated. From 15.9.1.1 of [ECMA-262](http://www.ecmascript.org/docs.php), edition 3 or 5 -- *Time is measured in ECMAScript in milliseconds since 01 January, 1970 UTC.* – Jonathan Lonowski Dec 02 '11 at 23:02
  • Possible duplicate of [How to format a JavaScript date](https://stackoverflow.com/questions/3552461/how-to-format-a-javascript-date) – Liam Aug 16 '18 at 08:31

7 Answers7

96

You can build it manually:

var m = new Date();
var dateString = m.getUTCFullYear() +"/"+ (m.getUTCMonth()+1) +"/"+ m.getUTCDate() + " " + m.getUTCHours() + ":" + m.getUTCMinutes() + ":" + m.getUTCSeconds();

and to force two digits on the values that require it, you can use something like this:

("0000" + 5).slice(-2)

Which would look like this:

var m = new Date();
var dateString =
    m.getUTCFullYear() + "/" +
    ("0" + (m.getUTCMonth()+1)).slice(-2) + "/" +
    ("0" + m.getUTCDate()).slice(-2) + " " +
    ("0" + m.getUTCHours()).slice(-2) + ":" +
    ("0" + m.getUTCMinutes()).slice(-2) + ":" +
    ("0" + m.getUTCSeconds()).slice(-2);

console.log(dateString);
Nhan
  • 3,422
  • 6
  • 28
  • 35
Joseph Marikle
  • 68,672
  • 14
  • 103
  • 120
  • 4
    `getUTCMonth` returns values in the range 0 - 11, so you'll want to add one before you convert to string. – dgvid Dec 02 '11 at 21:47
  • @dgvid gah! I always forget that! Thank you very much! – Joseph Marikle Dec 02 '11 at 21:49
  • 8
    This is quite ugly. Necessary, but ugly. – Jill-Jênn Vie May 28 '12 at 02:49
  • @RossPatterson—the Date object is mostly a copy of the Java date object of the same era (even down to the 2 digit year for *getYear*), so blame them. Days of the week are zero indexed too, as are hours, minutes and seconds. Why should months be different? ;-) – RobG Dec 08 '15 at 11:30
  • @RobG So we've got that going for us, which is nice. Now where did I put that quote about foolish consistency and hobgoblins? It must be around here someplace! :-) – Ross Patterson Dec 09 '15 at 01:18
34

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", " ");
MarredCheese
  • 9,495
  • 5
  • 59
  • 63
14

With jQuery date format :

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

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

Enjoy

Liam
  • 22,818
  • 25
  • 93
  • 157
user3452845
  • 149
  • 1
  • 2
2

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

Daniel Turcich
  • 1,494
  • 2
  • 21
  • 43
sean1093
  • 91
  • 1
  • 3
1

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."

dgvid
  • 24,815
  • 4
  • 37
  • 56
0

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

Nikos M.
  • 6,741
  • 3
  • 27
  • 38
0

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);
Lucke
  • 299
  • 3
  • 12