If you need slightly less control over formatting than the currently accepted answer, Date#toLocaleDateString can be used to create standard locale-specific renderings. The locale and options arguments let applications specify the language whose formatting conventions should be used, and allow some customization of the rendering.

Options key examples:

  1. day:
    The representation of the day.
    Possible values are "numeric", "2-digit".
  2. weekday:
    The representation of the weekday.
    Possible values are "narrow", "short", "long".
  3. year:
    The representation of the year.
    Possible values are "numeric", "2-digit".
  4. month:
    The representation of the month.
    Possible values are "numeric", "2-digit", "narrow", "short", "long".
  5. hour:
    The representation of the hour.
    Possible values are "numeric", "2-digit".
  6. minute: The representation of the minute.
    Possible values are "numeric", "2-digit".
  7. second:
    The representation of the second.
    Possible values are "numeric", 2-digit".
  8. hour12:
    The representation of time format.
    Accepts boolean true or false

All these keys are optional. You can change the number of options values based on your requirements, and this will also reflect the presence of each date time term.

Note: If you would only like to configure the content options, but still use the current locale, passing null for the first parameter will cause an error. Use undefined instead.

For different languages:

  1. "en-US": For American English
  2. "en-GB": For British English
  3. "hi-IN": For Hindi
  4. "ja-JP": For Japanese

You can use more language options.

For example

var options = { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' };
var today  = new Date();

console.log(today.toLocaleDateString("en-US")); // 9/17/2016
console.log(today.toLocaleDateString("en-US", options)); // Saturday, September 17, 2016
console.log(today.toLocaleDateString("hi-IN", options)); // शनिवार, 17 सितंबर 2016

You can also use the toLocaleString() method for the same purpose. The only difference is this function provides the time when you don't pass any options.

// Example
9/17/2016, 1:21:34 PM

References:

  • toLocaleString()

  • toLocaleDateString()

Answer from ajeet kanojia on Stack Overflow
🌐
W3Schools
w3schools.com › js › js_date_formats.asp
JavaScript Date Formats
JS Examples JS HTML DOM JS HTML Input JS HTML Objects JS HTML Events JS Browser JS Editor JS Exercises JS Quiz JS Website JS Syllabus JS Study Plan JS Interview Prep JS Bootcamp JS Certificate JS Reference ... The ISO format follows a strict standard in JavaScript. The other formats are not so well defined and might be browser specific. Independent of input format, JavaScript will (by default) output dates in full text string format:
Top answer
1 of 16
3084

If you need slightly less control over formatting than the currently accepted answer, Date#toLocaleDateString can be used to create standard locale-specific renderings. The locale and options arguments let applications specify the language whose formatting conventions should be used, and allow some customization of the rendering.

Options key examples:

  1. day:
    The representation of the day.
    Possible values are "numeric", "2-digit".
  2. weekday:
    The representation of the weekday.
    Possible values are "narrow", "short", "long".
  3. year:
    The representation of the year.
    Possible values are "numeric", "2-digit".
  4. month:
    The representation of the month.
    Possible values are "numeric", "2-digit", "narrow", "short", "long".
  5. hour:
    The representation of the hour.
    Possible values are "numeric", "2-digit".
  6. minute: The representation of the minute.
    Possible values are "numeric", "2-digit".
  7. second:
    The representation of the second.
    Possible values are "numeric", 2-digit".
  8. hour12:
    The representation of time format.
    Accepts boolean true or false

All these keys are optional. You can change the number of options values based on your requirements, and this will also reflect the presence of each date time term.

Note: If you would only like to configure the content options, but still use the current locale, passing null for the first parameter will cause an error. Use undefined instead.

For different languages:

  1. "en-US": For American English
  2. "en-GB": For British English
  3. "hi-IN": For Hindi
  4. "ja-JP": For Japanese

You can use more language options.

For example

var options = { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' };
var today  = new Date();

console.log(today.toLocaleDateString("en-US")); // 9/17/2016
console.log(today.toLocaleDateString("en-US", options)); // Saturday, September 17, 2016
console.log(today.toLocaleDateString("hi-IN", options)); // शनिवार, 17 सितंबर 2016

You can also use the toLocaleString() method for the same purpose. The only difference is this function provides the time when you don't pass any options.

// Example
9/17/2016, 1:21:34 PM

References:

  • toLocaleString()

  • toLocaleDateString()

2 of 16
1756

For custom-delimited date formats, you have to pull out the date (or time) components from a DateTimeFormat object (which is part of the ECMAScript Internationalization API), and then manually create a string with the delimiters you want.

To do this, you can use DateTimeFormat#formatToParts. You could destructure the array, but that is not ideal, as the array output depends on the locale:

{ // example 1
   let formatter = new Intl.DateTimeFormat('en');
   let example = formatter.formatToParts();
   console.log(example);
}
{ // example 2
   let formatter = new Intl.DateTimeFormat('hi');
   let example = formatter.formatToParts();
   console.log(example);
}

Better would be to map a format array to resultant strings:

function join(date, options, separator) {
   function format(option) {
      let formatter = new Intl.DateTimeFormat('en', option);
      return formatter.format(date);
   }
   return options.map(format).join(separator);
}

let options = [{day: 'numeric'}, {month: 'short'}, {year: 'numeric'}];
let joined = join(new Date, options, '-');
console.log(joined);

You can also pull out the parts of a DateTimeFormat one-by-one using DateTimeFormat#format, but note that when using this method, as of March 2020, there is a bug in the ECMAScript implementation when it comes to leading zeros on minutes and seconds (this bug is circumvented by the approach above).

let date = new Date(2010, 7, 5);
let year = new Intl.DateTimeFormat('en', { year: 'numeric' }).format(date);
let month = new Intl.DateTimeFormat('en', { month: 'short' }).format(date);
let day = new Intl.DateTimeFormat('en', { day: '2-digit' }).format(date);
console.log(`{month}-${year}`);

When working with dates and times, it is usually worth using a library (eg. luxon, date-fns, moment.js is not recommended for new projects) because of the many hidden complexities of the field.

Note that the ECMAScript Internationalization API, used in the solutions above is not supported in IE10 (0.03% global browser market share in Feb 2020).

🌐
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.
🌐
JavaScript.info
javascript.info › tutorial › the javascript language › data types
Date and time
So if you seriously want to understand performance, then please study how the JavaScript engine works. And then you probably won’t need microbenchmarks at all. The great pack of articles about V8 can be found at https://mrale.ph. The method Date.parse(str) can read a date from a string. The string format should be: YYYY-MM-DDTHH:mm:ss.sssZ, where:
🌐
Day.js
day.js.org › docs › en › display › format
Format · Day.js
dayjs().format() // current date in ISO8601, without fraction seconds e.g.
🌐
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 - Parsing User Input: Use the Date.parse() method or external libraries like Moment.js or Luxon to parse user-provided dates into valid Date objects. Validating User Input: Implement validation mechanisms to ensure the user's input adheres to the expected date format. Regular expressions or external libraries can help with this. Formatting dates in JavaScript is an essential skill when building web applications.
🌐
Codecademy
codecademy.com › article › javascript-date-format
How to Format a Date in JavaScript | Codecademy
To get a Date object for a specific date, we can pass the date as a string to the Date() constructor. ... You can pass the input date string to the Date() constructor in other formats as well, such as January 14, 2025 or 2025-01-14.
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Global_Objects › Intl › DateTimeFormat
Intl.DateTimeFormat - JavaScript | MDN
This method receives two Dates and formats the date range in the most concise way based on the locale and options provided when instantiating DateTimeFormat.
Find elsewhere
🌐
date-fns
date-fns.org
date-fns - modern JavaScript date utility library
date-fns provides the most comprehensive yet simple and consistent toolset for manipulating JavaScript dates in a browser & Node.js.
🌐
Medium
habtesoft.medium.com › 8-ways-of-date-formatting-in-javascript-1380625a1f50
8 Ways of Date Formatting in Javascript | by habtesoft | Medium
October 18, 2024 - const date = new Date(); // Default locale (browser's locale) console.log(date.toLocaleDateString()); // e.g., "9/20/2024" // Custom locale console.log(date.toLocaleDateString('en-GB')); // "20/09/2024" (dd/mm/yyyy) console.log(date.toLocal...
🌐
freeCodeCamp
freecodecamp.org › news › javascript-date-format-how-to-format-a-date-in-js
JavaScript Date Format – How to Format a Date in JS
November 7, 2024 - This article has taught you how to format dates in JavaScript, either from scratch or with the moment.js library.
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Global_Objects › Date › parse
Date.parse() - JavaScript | MDN
// Standard date-time string format const unixTimeZero = Date.parse("1970-01-01T00:00:00Z"); // Non-standard format resembling toUTCString() const javaScriptRelease = Date.parse("04 Dec 1995 00:12:00 GMT"); console.log(unixTimeZero); // Expected output: 0 console.log(javaScriptRelease); // Expected output: 818035920000 · js ·
🌐
LogRocket
blog.logrocket.com › home › how to format dates in javascript: methods, libraries, and best practices
How to format dates in JavaScript: Methods, libraries, and best practices - LogRocket Blog
May 8, 2025 - Here’s an example demonstrating how to set up Day.js with useful plugins for working with timezones, custom formats, and locales. We see how to create date objects from different input types, format them into readable strings, convert them to a specific timezone, and perform date math like adding or subtracting time—all while keeping the original dates immutable:
🌐
freeCodeCamp
freecodecamp.org › news › how-to-format-dates-in-javascript
How to Format Dates in JavaScript with One Line of Code
November 7, 2024 - Let’s take a look at two methods that you can use to format your dates in the best way so you can use them for your projects. The JavaScript toDateString() method returns the date portion of a date object in the form of a string using the following format:
🌐
Sentry
sentry.io › sentry answers › javascript › how do i format a date in javascript?
How do I Format a Date in JavaScript? | Sentry
const date = new Date(Date.UTC(2022, 10, 22, 9, 0, 0)); const dtf = new Intl.DateTimeFormat("de-DE", { dateStyle: "short", timeStyle: "long" }); console.log(dtf.format(date)); // 22.11.22, 11:00:00 GMT+2 · YoutubeHow Sentry.io saved me from disaster (opens in a new tab) ResourcesImprove Web Browser Performance - Find the JavaScript code causing slowdowns (opens in a new tab)
🌐
Built In
builtin.com › articles › js-formatting-date
How to Format Dates in JavaScript | Built In
The most common way to format dates in JavaScript is to use the date object: ... There are a few common JavaScript date libraries you can use for more flexible date options. These include: moment.js, Deprecated, date-fns, Luxon and Day.js.
🌐
Reddit
reddit.com › r/webdev › how get a date formatted like 2023-02-07 in js?
r/webdev on Reddit: How get a date formatted like 2023-02-07 in JS?
March 13, 2023 -

I'm going insane. I had this feature working perfectly. Took 2 weeks vacation. I come back and it's broken.

I know y'all will say this is impossible, but I was getting that format by using `date.toLocaleDateString('en-CA')`. I know the spec says that format is "dd/MM/yyyy", which isn't what I want, but I was giving me the format in the title, I swear to God.

This is such a stupid little thing but I've already spent hours on SO. It's just endless threads about people confused about datetimes and the differences between timezones and offsets and no one's talking about this silly little thing.

I have my new date: Wed Feb 08 2023 00:00:00 GMT-0500 (Eastern Standard Time)

I just need a simple operation to flip the string around so it becomes 2023-03-08

That is it. Please help

p.s. the date is always set to midnight user local time so offset can be ignored. Whatever day they're experiencing is the day to be formatted. Thank you

🌐
Stevenlevithan
blog.stevenlevithan.com › archives › javascript-date-format
JavaScript Date Format
Kris Kowal integrated Date Format 1.0 as a module into his innovative, emerging JavaScript library called Chiron. In the process, he changed it so that if only one argument is provided to dateFormat and that argument contains no numbers, it’s treated as a mask and applied to the current date and time.
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();

🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Global_Objects › Date › toLocaleDateString
Date.prototype.toLocaleDateString() - JavaScript | MDN
Basic use of this method without specifying a locale returns a formatted string in the default locale and with default options. js · const date = new Date(Date.UTC(2012, 11, 12, 3, 0, 0)); // toLocaleDateString() without arguments depends on the implementation, // the default locale, and the default time zone console.log(date.toLocaleDateString()); // "12/11/2012" if run in en-US locale with time zone America/Los_Angeles ·