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

Answer from Joseph Marikle on Stack Overflow
๐ŸŒ
MDN Web Docs
developer.mozilla.org โ€บ en-US โ€บ docs โ€บ Web โ€บ JavaScript โ€บ Reference โ€บ Global_Objects โ€บ Date
Date - JavaScript | MDN
There are many ways to format a date as a string. The JavaScript specification only specifies one format to be universally supported: the date time string format, a simplification of the ISO 8601 calendar date extended format.
๐ŸŒ
DEV Community
dev.to โ€บ diorla โ€บ a-guide-to-date-and-time-formatting-in-javascript-2ol2
A Guide to Date and Time Formatting in JavaScript - DEV Community
September 3, 2023 - Intl.DateTimeFormat is a powerful tool for formatting dates and times in JavaScript applications. It allows you to create user-friendly and localized date displays while customizing the format to meet your specific needs.
๐ŸŒ
W3Schools
w3schools.com โ€บ js โ€บ js_date_formats.asp
JavaScript Date Formats
The ISO 8601 syntax (YYYY-MM-DD) is also the preferred JavaScript date format:
๐ŸŒ
Envato Tuts+
code.tutsplus.com โ€บ home โ€บ javascript
Formatting JavaScript Dates | Envato Tuts+
July 30, 2023 - This code introduces the formatTime() function, which accepts two parameters: a JavaScript Date object and a numeric value indicating whether the time should be formatted in 12-hour (AM/PM) or the default 24-hour format.
๐ŸŒ
MDN Web Docs
developer.mozilla.org โ€บ en-US โ€บ docs โ€บ Web โ€บ JavaScript โ€บ Reference โ€บ Global_Objects โ€บ Intl โ€บ DateTimeFormat
Intl.DateTimeFormat - JavaScript | MDN
In order to get the format of the language used in the user interface of your application, make sure to specify that language (and possibly some fallback languages) using the locales argument: ... const date = new Date(Date.UTC(2012, 11, 20, 3, 0, 0)); // Results below use the time zone of America/Los_Angeles (UTC-0800, Pacific Standard Time) // US English uses month-day-year order console.log(new Intl.DateTimeFormat("en-US").format(date)); // "12/19/2012" // British English uses day-month-year order console.log(new Intl.DateTimeFormat("en-GB").format(date)); // "19/12/2012" // Korean uses year-month-day order console.log(new Intl.DateTimeFormat("ko-KR").format(date)); // "2012.
๐ŸŒ
Moment.js
momentjs.com
Moment.js | Home
moment().format('MMMM Do YYYY, h:mm:ss a'); moment().format('dddd'); moment().format("MMM Do YY"); moment().format('YYYY [escaped] YYYY'); moment().format();
๐ŸŒ
Tabnine
tabnine.com โ€บ home โ€บ how to format date in javascript
How to Format Date in JavaScript - Tabnine
July 25, 2024 - This second parameter allows us to define the formatting for each part of the outcome result individually โ€“ the comments show the possible values for each potential key in the argument. At this point, weโ€™ve only scratched the surface of the things you can do with JavaScriptโ€™s Date() function.
Find elsewhere
๐ŸŒ
freeCodeCamp
freecodecamp.org โ€บ news โ€บ how-to-format-dates-in-javascript
How to Format Dates in JavaScript with One Line of Code
November 7, 2024 - The most used method to get the date in JavaScript is the new Date() object. By default, when you run new Date() in your terminal, it uses your browser's time zone and displays the date as a full text string, like Fri Jul 02 2021 12:44:45 GMT+0100 (British Summer Time). But having something like this in your web page or application is not professional and isn't easy to read. So this forces you to look for better ways to format these dates.
Top answer
1 of 16
277

You may want to try

var d = new Date();
d.toLocaleString();       // -> "2/1/2013 7:37:08 AM"
d.toLocaleDateString();   // -> "2/1/2013"
d.toLocaleTimeString();  // -> "7:38:05 AM"

Documentation

2 of 16
219

A JavaScript Date has several methods allowing you to extract its parts:

getFullYear() - Returns the 4-digit year
getMonth() - Returns a zero-based integer (0-11) representing the month of the year.
getDate() - Returns the day of the month (1-31).
getDay() - Returns the day of the week (0-6). 0 is Sunday, 6 is Saturday.
getHours() - Returns the hour of the day (0-23).
getMinutes() - Returns the minute (0-59).
getSeconds() - Returns the second (0-59).
getMilliseconds() - Returns the milliseconds (0-999).
getTimezoneOffset() - Returns the number of minutes between the machine local time and UTC.

There are no built-in methods allowing you to get localized strings like "Friday", "February", or "PM". You have to code that yourself. To get the string you want, you at least need to store string representations of days and months:

var months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
var days = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];

Then, put it together using the methods above:

var months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
var days = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
var d = new Date();
var day = days[d.getDay()];
var hr = d.getHours();
var min = d.getMinutes();
if (min < 10) {
    min = "0" + min;
}
var ampm = "am";
if( hr > 12 ) {
    hr -= 12;
    ampm = "pm";
}
var date = d.getDate();
var month = months[d.getMonth()];
var year = d.getFullYear();
var x = document.getElementById("time");
x.innerHTML = day + " " + hr + ":" + min + ampm + " " + date + " " + month + " " + year;
<span id="time"></span>

I have a date format function I like to include in my standard library. It takes a format string parameter that defines the desired output. The format strings are loosely based on .Net custom Date and Time format strings. For the format you specified the following format string would work: "dddd h:mmtt d MMM yyyy".

var d = new Date();
var x = document.getElementById("time");
x.innerHTML = formatDate(d, "dddd h:mmtt d MMM yyyy");

Demo: jsfiddle.net/BNkkB/1

Here is my full date formatting function:

const MMMM = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
const MMM = MMMM.map(m => m.slice(0, 3));
const dddd = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
const ddd = dddd.map(d => d.slice(0, 3));

function ii(i, len = 2) {
    return (i + "").padStart(len, "0");
}

function tzHHMM(tz) {
    const sign = tz > 0 ? "-" : "+"; // +08:00 == -480, signs are reversed
    const tzv = Math.abs(tz);
    const tzHrs = Math.floor(tzv / 60);
    const tzMin = tzv % 60;
    return sign + ii(tzHrs) + ":" + ii(tzMin);
}

function formatDate(date, format, utc) {
    const y = utc ? date.getUTCFullYear() : date.getFullYear();
    const M = utc ? date.getUTCMonth() : date.getMonth();
    const d = utc ? date.getUTCDate() : date.getDate();
    const H = utc ? date.getUTCHours() : date.getHours();
    const h = H > 12 ? H - 12 : H == 0 ? 12 : H;
    const m = utc ? date.getUTCMinutes() : date.getMinutes();
    const s = utc ? date.getUTCSeconds() : date.getSeconds();
    const f = utc ? date.getUTCMilliseconds() : date.getMilliseconds();
    const TT = H < 12 ? "AM" : "PM";
    const tt = TT.toLowerCase();
    const day = utc ? date.getUTCDay() : date.getDay();
    const replacements = {
        y,
        yy: y.toString().slice(-2),
        yyy: y,
        yyyy: y,
        M,
        MM: ii(M),
        MMM: MMM[M],
        MMMM: MMMM[M],
        d,
        dd: ii(d),
        ddd: ddd[day],
        dddd: dddd[day],
        H,
        HH: ii(H),
        h,
        hh: ii(h),
        m,
        mm: ii(m),
        s,
        ss: ii(s),
        f: Math.round(f / 100),
        ff: ii(Math.round(f / 10)),
        fff: ii(f, 3),
        ffff: ii(f * 10, 4),
        T: TT[0],
        TT,
        t: tt[0],
        tt,
        K: utc ? "Z" : tzHHMM(date.getTimezoneOffset()),
        "\\": "",
    };
    return format.replace(/(?:\\(?=.)|(?<!\\)(?:([yMdf])\1{0,3}|([HhmsTt])\2?|K))/g, $0 => replacements[$0]);
}
๐ŸŒ
Bugfender
bugfender.com โ€บ blog โ€บ javascript-date-and-time
The Definitive Guide to JavaScript Date and Time | Bugfender
February 18, 2025 - We have seen some of them while discussing how to create a Date object. However, the ECMAScript Internationalization(Intl) API provides a more flexible way to handle date-time format in JavaScript. You can create language-sensitive (in other words, locale-aware formats) date and time using the Intl.DateTimeFormat API.
๐ŸŒ
Vishalgarg
vishalgarg.io โ€บ articles โ€บ how-to-format-a-date-in-javascript
How to Format a Date in JavaScript, Date Formatting in JS - Vishal Garg
April 4, 2025 - 1const date = new Date('2023-10-01T12:00:00Z'); 2const options = { 3 day: '2-digit', 4 month: '2-digit', 5 year: 'numeric', 6}; 7const formatter = new Intl.DateTimeFormat('en-GB', options); 8const formattedDate = formatter.format(date); 9console.log(formattedDate); // Outputs: 01/10/2023 Using Intl.DateTimeFormat, you can specify the desired locale and various options to format dates precisely as needed. There are more options you can use in the Intl.DateTimeFormat object, such as hour, minute, second, weekday, etc. You can refer to the MDN documentation for more details on the available options. When working with dates and times, it's essential to consider time zones, especially if your application is used in different regions. JavaScript provides several ways to handle time zones:
Top answer
1 of 5
153

Yes, you can use the native javascript Date() object and its methods.

For instance you can create a function like:

function formatDate(date) {
  var hours = date.getHours();
  var minutes = date.getMinutes();
  var ampm = hours >= 12 ? 'pm' : 'am';
  hours = hours % 12;
  hours = hours ? hours : 12; // the hour '0' should be '12'
  minutes = minutes < 10 ? '0'+minutes : minutes;
  var strTime = hours + ':' + minutes + ' ' + ampm;
  return (date.getMonth()+1) + "/" + date.getDate() + "/" + date.getFullYear() + "  " + strTime;
}

var d = new Date();
var e = formatDate(d);

alert(e);

And display also the am / pm and the correct time.

Remember to use getFullYear() method and not getYear() because it has been deprecated.

DEMO http://jsfiddle.net/a_incarnati/kqo10jLb/4/

2 of 5
94

Please do not reinvent the wheel. There are many open-source and COTS solutions that already exist to solve this problem.

Recommended

The following libraries are recommended for new projects.

Luxon (timezones, successor to Moment)

Luxon is the successor to the Moment.js library. It has native time zone and Intl support.

const { DateTime } = luxon;

const value = DateTime
  .fromFormat("2014-08-20 15:30:00", "yyyy-MM-dd HH:mm:ss")
  .toFormat('MM/dd/yyyy h:mm a');

console.log(value); // 08/20/2014 3:30 PM
<script src="https://cdnjs.cloudflare.com/ajax/libs/luxon/3.3.0/luxon.min.js"></script>

js-joda (fixes the Date object)

This is a port of the Joda-Time library in Java. Joda-Time became the java.time package in the Java JDK in version 1.8. It is the successor to the Date object and improves it significantly.

const { DateTimeFormat, DateTimeFormatter, LocalDateTime } = JSJoda;
const { Locale } = JSJodaLocale;

const value = LocalDateTime
  .parse('2014-08-20 15:30:00',
    DateTimeFormatter.ofPattern('yyyy-M-d HH:mm:ss'))
  .format(DateTimeFormatter.ofPattern('MM/dd/yyyy h:mm a')
    .withLocale(Locale.US));
  
console.log(value); // 08/20/2014 3:30 PM
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js-joda.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/@js-joda/[email protected]/dist/index.min.js"></script>

date-fns (fast, tree-shaking, server-side)

This is version 1.x, if you are using Node.js or another server-side JavaScript engine, you should use version 2.x.

const value = dateFns.format(
  dateFns.parse("2014-08-20 15:30:00", "yyyy-MM-dd HH:mm:ss"),
  'MM/DD/YYYY h:mm a');

console.log(value); // 08/20/2014 3:30 pm
<script src="https://cdnjs.cloudflare.com/ajax/libs/date-fns/1.30.1/date_fns.min.js"></script>

Day.js (smallest footprint)

A minimalist date library with plugins.

const value = dayjs("2014-08-20 15:30:00", "yyyy-MM-dd HH:mm:ss")
  .format('MM/DD/YYYY h:mm a');

console.log(value); // 08/20/2014 3:30 pm
<script src="https://cdnjs.cloudflare.com/ajax/libs/dayjs/1.11.7/dayjs.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/dayjs/1.11.7/plugin/customParseFormat.min.js"></script>

date-and-time (small footprint)

A minimalist date library with plugins.

const value = date.format(
  date.parse("2014-08-20 15:30:00", "YYYY-MM-DD HH:mm:ss"),
  'MM/DD/YYYY h:mm A');

console.log(value); // 08/20/2014 3:30 PM
<script src="https://cdn.jsdelivr.net/npm/[email protected]/date-and-time.min.js"></script>

Not recommended

The following libraries are not recommended for new projects, because they are either no longer supported or do not follow best practices.

Moment (timezones, legacy)

Here is the original version using Moment. Since Luxon is the successor to Moment, I have included this as an alternative.

const value = moment('2014-08-20 15:30:00').format('MM/DD/YYYY h:mm a');

console.log(value); // 08/20/2014 3:30 pm
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.4/moment.min.js"></script>

Date.js (small footprint, archived)

This library manipulates the Date prototype. This is not considered best practice.

const value = Date.parse('2014-08-20 15:30:00').toString('MM/dd/yyyy hh:mm tt');

console.log(value); // 08/20/2014 03:30 PM
<script src="https://cdnjs.cloudflare.com/ajax/libs/datejs/1.0/date.min.js"></script>

Without a library

Now, if you really don't want to use a library, a simple tokenizer can assist you in parsing and formatting.

const TOKENS = new Set(['Y', 'M', 'D', 'H', 'h', 'm', 's', 'a']);

const main = () => {
  const value = format(parse('2014-08-20 15:30:00', 'YYYY-MM-DD HH:mm:ss'), 'MM/DD/YYYY h:mm a');
  console.log(value); // 08/20/2014 3:30 pm
};

const parse = (input, pattern) =>
  (tokens => new Date(
    +tokens['Y'] , +tokens['M'] - 1 , +tokens['D'],
    +tokens['H'] , +tokens['m']     , +tokens['s']
  ))(tokenize(input, pattern));

const format = (date, pattern) =>
  pattern.replace(/\b(\w)(\1)*\b/g, (match) => {
    switch (match[0]) {
      case 'Y': return date.getFullYear();
      case 'M': return `${date.getMonth() + 1}`.padStart(match.length, '0');
      case 'D': return `${date.getDate()}`.padStart(match.length, '0');
      case 'h': return `${date.getHours() % 12}`.padStart(match.length, '0');
      case 'm': return `${date.getMinutes()}`.padStart(match.length, '0');
      case 'a': return date.getHours() < 12 ? 'am' : 'pm';
    }
    return capture;
  });

const tokenize = (input, pattern) => 
  pattern.split('').reduce((acc, token, index) => TOKENS.has(token)
    ? { ...acc, [token]: (acc[token] ?? '') + input[index] }
    : acc, {});

main();

๐ŸŒ
Chris Pietschmann
pietschsoft.com โ€บ post โ€บ 2023 โ€บ 09 โ€บ 28 โ€บ javascript-format-date-to-string
JavaScript: Format Date to String | Chris Pietschmann
September 28, 2023 - In this example, we use Intl.DateTimeFormat to format the Date object based on locale-specific rules and options. Formatting a JavaScript Date object as a string is a common task in web development. While JavaScript doesnโ€™t provide a built-in method for this, you can achieve it easily by creating a custom formatting function or using libraries such as date-fns or Intl.DateTimeFormat.
๐ŸŒ
freeCodeCamp
freecodecamp.org โ€บ news โ€บ how-to-format-a-date-with-javascript-date-formatting-in-js
How to Format a Date with JavaScript โ€“ Date Formatting in JS
November 7, 2024 - Specific Date Format: To display a date in a specific format, such as DD/MM/YYYY, you can use Intl.DateTimeFormat with the appropriate options.
๐ŸŒ
Day.js
day.js.org โ€บ docs โ€บ en โ€บ display โ€บ format
Format ยท Day.js
'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'
๐ŸŒ
Codecademy
codecademy.com โ€บ article โ€บ javascript-date-format
How to Format a Date in JavaScript | Codecademy
format(): This method formats the given date according to the time format specified in the DateTimeFormat object (DD/MM/YYYY). ... By understanding these techniques, we can efficiently customize the format of a date according to our preferences.
๐ŸŒ
JavaScript.info
javascript.info โ€บ tutorial โ€บ the javascript language โ€บ data types
Date and time
Otherwise, the full date in the format "DD.MM.YY HH:mm". That is: "day.month.year hours:minutes", all in 2-digit format, e.g.
๐ŸŒ
TutorialsPoint
tutorialspoint.com โ€บ javascript โ€บ javascript_date_formats.htm
JavaScript - Date Formats
This example gives us a deeper understanding of the customized date formats which do not have any prefix format and are up to the developer choose. We use the Intl.DateTimeFormat object to create our format of (weekday, month, day, year). With this option customized date formats we can choose not only the parts of the date to be made visible but also their order.