If you're using Node.js, you're sure to have EcmaScript 5, and so Date has a toISOString method. You're asking for a slight modification of ISO8601:

new Date().toISOString()
> '2012-11-04T14:51:06.157Z'

So just cut a few things out, and you're set:

new Date().toISOString().
  replace(/T/, ' ').      // replace T with a space
  replace(/\..+/, '')     // delete the dot and everything after
> '2012-11-04 14:55:45'

Or, in one line: new Date().toISOString().replace(/T/, ' ').replace(/\..+/, '')

ISO8601 is necessarily UTC (also indicated by the trailing Z on the first result), so you get UTC by default (always a good thing).

Answer from chbrown on Stack Overflow
🌐
Node-RED
discourse.nodered.org › general
Format date at 'YYYY:MM:DD HH:MM;SS' - General - Node-RED Forum
November 23, 2023 - Hello. How can you format the date in the logs? now I have it '23 Nov 2023 hh:mm:ss' it must have been so 'YYYY:MM:DD HH:MM;SS' Writing a function just adds the date again(( const currentDate = new Date(); const formattedDateTime = currentDate.toISOString().replace(/T/, ' ').replace(/\..+/, ''); const { loggingLevel } = msg; delete msg.loggingLevel; const messageToLog = `${formattedDateTime} - [info] [function:Log message to system console] ${JSON.stringify(msg)}`; if (loggingLevel === '...
🌐
GeeksforGeeks
geeksforgeeks.org › node.js › how-to-format-the-current-date-in-mm-dd-yyyy-hhmmss-format-using-node-js
How to format the current date in MM/DD/YYYY HH:MM:SS format using Node? - GeeksforGeeks
July 23, 2025 - const date = new Date(); // Function ... = { dd: formatData(date.getDate()), mm: formatData(date.getMonth() + 1), yyyy: date.getFullYear(), HH: formatData(date.getHours()), hh: formatData(formatHour(date.getHours())), MM: formatData(date.getMinutes()), SS: formatData(date.getSeconds()), };...
Top answer
1 of 16
731

If you're using Node.js, you're sure to have EcmaScript 5, and so Date has a toISOString method. You're asking for a slight modification of ISO8601:

new Date().toISOString()
> '2012-11-04T14:51:06.157Z'

So just cut a few things out, and you're set:

new Date().toISOString().
  replace(/T/, ' ').      // replace T with a space
  replace(/\..+/, '')     // delete the dot and everything after
> '2012-11-04 14:55:45'

Or, in one line: new Date().toISOString().replace(/T/, ' ').replace(/\..+/, '')

ISO8601 is necessarily UTC (also indicated by the trailing Z on the first result), so you get UTC by default (always a good thing).

2 of 16
135

UPDATE 2021-10-06: Added Day.js and remove spurious edit by @ashleedawg
UPDATE 2021-04-07: Luxon added by @Tampa.
UPDATE 2021-02-28: It should now be noted that Moment.js is no longer being actively developed. It won't disappear in a hurry because it is embedded in so many other things. The website has some recommendations for alternatives and an explanation of why.
UPDATE 2017-03-29: Added date-fns, some notes on Moment and Datejs
UPDATE 2016-09-14: Added SugarJS which seems to have some excellent date/time functions.


OK, since no one has actually provided an actual answer, here is mine.

A library is certainly the best bet for handling dates and times in a standard way. There are lots of edge cases in date/time calculations so it is useful to be able to hand-off the development to a library.

Here is a list of the main Node compatible time formatting libraries:

  • Day.js [added 2021-10-06] "Fast 2kB alternative to Moment.js with the same modern API"
  • Luxon [added 2017-03-29, thanks to Tampa] "A powerful, modern, and friendly wrapper for JavaScript dates and times." - MomentJS rebuilt from the ground up with immutable types, chaining and much more.
  • Moment.js [thanks to Mustafa] "A lightweight (4.3k) javascript date library for parsing, manipulating, and formatting dates" - Includes internationalization, calculations and relative date formats - Update 2017-03-29: Not quite so light-weight any more but still the most comprehensive solution, especially if you need timezone support. - Update 2021-02-28: No longer in active development.
  • date-fns [added 2017-03-29, thanks to Fractalf] Small, fast, works with standard JS date objects. Great alternative to Moment if you don't need timezone support.
  • SugarJS - A general helper library adding much needed features to JavaScripts built-in object types. Includes some excellent looking date/time capabilities.
  • strftime - Just what it says, nice and simple
  • dateutil - This is the one I used to use before MomentJS
  • node-formatdate
  • TimeTraveller - "Time Traveller provides a set of utility methods to deal with dates. From adding and subtracting, to formatting. Time Traveller only extends date objects that it creates, without polluting the global namespace."
  • Tempus [thanks to Dan D] - UPDATE: this can also be used with Node and deployed with npm, see the docs

There are also non-Node libraries:

  • Datejs [thanks to Peter Olson] - not packaged in npm or GitHub so not quite so easy to use with Node - not really recommended as not updated since 2007!
Top answer
1 of 4
181

[Addendum 12/2022]: Here's a library to format dates using Intl.DateTimeFormat.

[Addendum 01/2024]: And here is a (ES-)Date manipulation library

Try something like this

var d = new Date,
    dformat = [d.getMonth()+1,
               d.getDate(),
               d.getFullYear()].join('/')+' '+
              [d.getHours(),
               d.getMinutes(),
               d.getSeconds()].join(':');

If you want leading zero's for values < 10, use this number extension

Number.prototype.padLeft = function(base,chr){
    var  len = (String(base || 10).length - String(this).length)+1;
    return len > 0? new Array(len).join(chr || '0')+this : this;
}
// usage
//=> 3..padLeft() => '03'
//=> 3..padLeft(100,'-') => '--3' 

Applied to the previous code:

var d = new Date,
    dformat = [(d.getMonth()+1).padLeft(),
               d.getDate().padLeft(),
               d.getFullYear()].join('/') +' ' +
              [d.getHours().padLeft(),
               d.getMinutes().padLeft(),
               d.getSeconds().padLeft()].join(':');
//=> dformat => '05/17/2012 10:52:21'

See this code in [jsfiddle][1]

[edit 2019] Using ES20xx, you can use a template literal and the new padStart string extension.

const dt = new Date();
const padL = (nr, len = 2, chr = `0`) => `${nr}`.padStart(2, chr);

console.log(`${
    padL(dt.getMonth()+1)}/${
    padL(dt.getDate())}/${
    dt.getFullYear()} ${
    padL(dt.getHours())}:${
    padL(dt.getMinutes())}:${
    padL(dt.getSeconds())}`
);

2 of 4
73

You can always format a date by extracting the parts and combine them using string functions in desired order:

function formatDate(date) {
  let datePart = [
    date.getMonth() + 1,
    date.getDate(),
    date.getFullYear()
  ].map((n, i) => n.toString().padStart(i === 2 ? 4 : 2, "0")).join("/");
  let timePart = [
    date.getHours(),
    date.getMinutes(),
    date.getSeconds()
  ].map((n, i) => n.toString().padStart(2, "0")).join(":");
  return datePart + " " + timePart;
}

let date = new Date();
console.log("%o => %s", date, formatDate(date));

🌐
W3Schools
w3schools.com › js › js_date_formats.asp
JavaScript Date Formats
ISO dates can be written with added hours, minutes, and seconds (YYYY-MM-DDTHH:MM:SSZ): const d = new Date("2015-03-25T12:00:00Z"); Try it Yourself » · Date and time is separated with a capital T. UTC time is defined with a capital letter Z. If you want to modify the time relative to UTC, remove the Z and add +HH:MM or -HH:MM instead:
🌐
Medium
trymysolution.medium.com › javascript-date-as-in-yyyy-mm-dd-hh-mm-ss-format-or-mm-dd-yyyy-hh-mm-ss-a0c96e8fa888
JavaScript Date as in YYYY-MM-DD hh:mm:ss Format or MM/DD/YYYY hh:mm:ss | by Yogesh D V | Medium
April 11, 2023 - function padTwoDigits(num: number) ... string = "-") { // :::: Exmple Usage :::: // The function takes a Date object as a parameter and formats the date as YYYY-MM-DD hh:mm:ss....
🌐
W3docs
w3docs.com › javascript
How to Format a JavaScript Date
You should use dateformat as a method and pass the Date object: const dateformat = require('dateformat'); let now = new Date(); dateformat(now, 'dddd, mmmm dS, yyyy, h:MM:ss TT'); 'Tuesday, Feb 2nd, 2020, 4:30:20 PM'
Find elsewhere
🌐
GitHub
gist.github.com › mohokh67 › e0c5035816f5a88d6133b085361ad15b
Get YYYY-MM-DD HH-MM-SS in JavaScript · GitHub
Clone this repository at &lt;script src=&quot;https://gist.github.com/mohokh67/e0c5035816f5a88d6133b085361ad15b.js&quot;&gt;&lt;/script&gt; Save mohokh67/e0c5035816f5a88d6133b085361ad15b to your computer and use it in GitHub Desktop. Download ZIP · Get YYYY-MM-DD HH-MM-SS in JavaScript ·
🌐
npm
npmjs.com › package › dateformat
dateformat - npm
import dateFormat, { masks } from "dateformat"; const now = new Date(); // Basic usage dateFormat(now, "dddd, mmmm dS, yyyy, h:MM:ss TT"); // Saturday, June 9th, 2007, 5:46:21 PM // You can use one of several named masks dateFormat(now, "isoDateTime"); // 2007-06-09T17:46:21 // ...Or add your own masks.hammerTime = 'HH:MM!
      » npm install dateformat
    
Published   Feb 19, 2022
Version   5.0.3
Author   Steven Levithan
🌐
Reddit
reddit.com › r/node › everything you need to know to master dates in javascript
r/node on Reddit: Everything you need to know to master dates in JavaScript
April 28, 2024 -

Dates in JavaScript are very annoying to deal with. So in this post, I will show you a basic of dates in JS to help you get started with this tedious API.

I've also made a video on this topic, so if a video is more to you're liking then you can check it out here.

1. Epoch

  • The epoch is a specific time that the JS date API started its timestamp count.

  • The date is 1970-01-01.

2. The date class

  • The date class in JS is a used to create a new date object which has the value of the one passed as the constructor.

    new Date("2016-02-12");

  • In case you don't provide a date the new object will have the value of the current date.

3. The date format

  • The most used and default format for displaying dates is the YYYY-MM-DDTHH:mm:ss.sssZ format.

    YYYY: Year MM: Month DD: Date T: Separator of the date from the time HH: Hour mm: Minute ss: Second sss: Millisecond Z: time zone

4. Date methods

  • Date.parse(): This method is used to change the above format and any other string format of dates into a timestamp that starts it's count from the epoch.

  • Date.now(): Returns the current date using a parsed timestamp format.

  • Date.UTC(): Creates a date based on the UTC(Universal Time Coordinate) time zone.

5. Date creation

  • Regular date creation.

    new Date();

  • Date creation with custom date.

    new Date("2012-12-12");

  • Date creation with arguments following the YYYY-MM-DDTHH:mm:ss.sss format.

    new Date(1998, 12, 11, 9, 30, 30, 998);

6. Date formating

  • The default date follows the above YYYY-MM-DDTHH:mm:ss.sssZ format.

  • Using Date.parse() you can convert any date into a timestamp format.

  • You can also use dates as strings:

    const date = new Date();

    date.toDateString(); // Thu Sept 12 2024

    date.toTimeString(); // 12:00:33

    date.toLocalDateString(); // Uses the current user's time zone to display date.

    date.toLocalTimeString(); // Uses the current user's time zone to display time.

    date.toISOString(); // Uses the default date format.

7. Date components

  • Date.getFullYear(): Returns the year only.

  • Date.getMonth(): Returns the month only with a zero based indexing format meaning January will be displayed as 0 and February as 1, etc.

  • Date.getDate(): Returns the date only.

  • Date.getHours(): Returns the hour only.

  • Date.getMinutes(): Returns the minute only.

  • Date.getSeconds(): Returns the hour only.

  • Date.getMilliseconds(): Returns the milliseconds only.

Conclusion

This is not the only functionality that the JS date API has but it's good starting point for you to keep on learning. Dates in JS could be frustrating at times but they are a very powerful tool that every developer should have at least a basic knowledge of.

For a more detailed look at the date API in JS take a look at my video here.

🌐
Byby
byby.dev › js-format-date
How to parse and format a date in JavaScript
- ISO 8601: YYYY-MM-DDTHH:mm:ss.sssZ (e.g. 2022-05-30T00:00:00.000Z) - Short date: mm/dd/yyyy or dd/mm/yyyy (e.g. 04/24/2023 or 24/04/2023) - Long date: MMMM dd, yyyy (e.g. April 24, 2023) - RFC 2822: EEE, dd MMM yyyy HH:mm:ss GMT (e.g. Mon, 24 Apr 2023 00:00:00 GMT) - Unix timestamp: the number ...
🌐
TutorialsPoint
tutorialspoint.com › how-to-convert-a-date-object-to-string-with-format-hh-mm-ss-in-javascript
How to convert a date object to string with format hh:mm:ss in JavaScript?
The Moment.JS library for the date ... requirements. Users can follow the syntax below to use the moment().format() method. let date = moment(); let dateStr = date.format("YY-MM-DD HH:mm:ss");...
🌐
JavaScript.info
javascript.info › tutorial › the javascript language › data types
Date and time
The string format should be: YYYY-MM-DDTHH:mm:ss.sssZ, where: YYYY-MM-DD – is the date: year-month-day. The character "T" is used as the delimiter. HH:mm:ss.sss – is the time: hours, minutes, seconds and milliseconds.
🌐
DEV Community
dev.to › riversun › introducing-a-handy-javascript-date-formatting-function-5cd7
Introducing a handy JavaScript date formatting function. - DEV Community
February 19, 2020 - I created A function to format the date (Date object) with a pattern like yyyy-MM-dd'T'HH:mm:ssXXX in JavaScript. With this function alone, ISO8601 format, RFC1123 format, time zone RFC822, etc. can be expressed.
🌐
GeeksforGeeks
geeksforgeeks.org › node.js › node-js-date-format-api
Node.js Date.format() API - GeeksforGeeks
January 8, 2025 - // Node.js program to demonstrate ... // Formatting the date and time // by using date.format() method const value = date.format(now,'YYYY/MM/DD HH:mm:ss'); // Display the result console.log("current date and time : " + ...
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Global_Objects › Date
Date - JavaScript | MDN
DD is the day of the month, with two digits (01 to 31). Defaults to 01. T is a literal character, which indicates the beginning of the time part of the string. The T is required when specifying the time part. HH is the hour, with two digits (00 to 23). As a special case, 24:00:00 is allowed, ...
🌐
Day.js
day.js.org › docs › en › display › format
Format · Day.js
dayjs().format() // current date in ISO8601, without fraction seconds e.g. '2020-04-02T08:02:17-05:00' dayjs('2019-01-25').format('[YYYYescape] YYYY-MM-DDTHH:mm:ssZ[Z]') // 'YYYYescape 2019-01-25T00:00:00-02:00Z' dayjs('2019-01-25').format('DD/MM/YYYY') // '25/01/2019'