2671

In JavaScript, how can I format a date object to print as 10-Aug-2010?

leonheess
  • 5,825
  • 6
  • 42
  • 67
leora
  • 163,579
  • 332
  • 834
  • 1,328
  • 257
    As usual: beware THE MONTH is ZERO-INDEXED ! So January is zero not one... – Christophe Roussy Nov 19 '15 at 12:45
  • 16
    Also beware, `myDate.getDay()` doesn't return the day of week, but the **location of the weekday** related to the week. `myDate.getDate()` returns the **current weekday**. – Jimenemex Aug 18 '17 at 19:47
  • 4
    For formatting DateTimes in javascript use the `Intl.DateTimeFormat` object. I describe it in my post: [Post](https://stackoverflow.com/a/46728347/7487135). I create an online solution for your answer by `Intl.DateTimeFormat` [Check Online](https://jsbin.com/buvaketoho/5/edit?js,console) – Iman Bahrampour Oct 13 '17 at 11:05
  • 6
    You can use `toLocaleDateString ` – onmyway133 Nov 05 '18 at 13:50
  • 2
    @onmyway you actually can't. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleFormat – ahnbizcad Jan 19 '19 at 04:34

58 Answers58

2324

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

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 English
  2. "hi-IN": For Hindi
  3. "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:

Ben Aston
  • 45,997
  • 54
  • 176
  • 303
ajeet kanojia
  • 23,273
  • 1
  • 7
  • 7
  • [this](https://mdn-mixmix.hashbase.io/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleFormat.html) says its a non standard, but [mozzilla](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleDateString) doesn't specify that – Pankaj Phartiyal Nov 16 '17 at 19:42
  • 28
    Seems like this answer should be the best "current" answer. Also used the option "hour12: true" to use 12-hour vs 24-hour format. Maybe should be added to your summary list in the answer. – Doug Knudsen Dec 17 '17 at 17:08
  • `timeZoneName` option doesn't works in IE (tested in IE 11) – Sandeep Kumar Aug 29 '18 at 22:12
  • 13
    @Iarwa1n This answer hasn't mentioned but you can use toLocaleDateString to return only certain parts that you can then join as you wish. Check my answer below. `date.toLocaleDateString("en-US", { day: 'numeric' }) + "-"+ date.toLocaleDateString("en-US", { month: 'short' }) + "-" + date.toLocaleDateString("en-US", { year: 'numeric' })` should give `16-Nov-2019` – K Vij Nov 27 '19 at 20:33
  • 2
    It was a long long dig of following links, but I found where they're hidden @MosesSchwartz: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/DateTimeFormat – B T Sep 06 '20 at 07:42
  • @KVij—that's a very inefficient way to go about formatting a date, especially considering there is a [*formatToParts* method](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/formatToParts) that returns all the parts in an array of objects. – RobG Dec 18 '20 at 07:00
1555

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 f = new Intl.DateTimeFormat('en');
   let a = f.formatToParts();
   console.log(a);
}
{ // example 2
   let f = new Intl.DateTimeFormat('hi');
   let a = f.formatToParts();
   console.log(a);
}

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

function join(t, a, s) {
   function format(m) {
      let f = new Intl.DateTimeFormat('en', m);
      return f.format(t);
   }
   return a.map(format).join(s);
}

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

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 d = new Date(2010, 7, 5);
let ye = new Intl.DateTimeFormat('en', { year: 'numeric' }).format(d);
let mo = new Intl.DateTimeFormat('en', { month: 'short' }).format(d);
let da = new Intl.DateTimeFormat('en', { day: '2-digit' }).format(d);
console.log(`${da}-${mo}-${ye}`);

When working with dates and times, it is usually worth using a library (eg. moment.js, luxon) 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).

Steven Penny
  • 82,115
  • 47
  • 308
  • 348
Marko
  • 68,081
  • 26
  • 118
  • 153
  • 1
    Or extend the `Date` object, like I did at http://stackoverflow.com/questions/3187790/convert-unix-time-to-mm-dd-yy-hhmm-24-hour-in-javascript/3189792#3189792 – Marcel Korpel Aug 23 '10 at 23:41
  • 12
    I get that `ye` is year, `mo` is month and `da` is day. What is `o`? What is `a`? What is `m`? Could you please use proper variable names? – mikemaccana Jan 19 '21 at 20:41
641

Use the date.format library:

var dateFormat = require('dateformat');
var now = new Date();
dateFormat(now, "dddd, mmmm dS, yyyy, h:MM:ss TT");

returns:

Saturday, June 9th, 2007, 5:46:21 PM 

dateformat on npm

http://jsfiddle.net/phZr7/1/

Stephan Muller
  • 24,574
  • 14
  • 80
  • 119
RobertPitt
  • 54,473
  • 20
  • 110
  • 156
  • His code for "L" for cantiseconds is wrong, he should remove "L > 99 ?" part... Other than that, it's pretty neat, if not too well localizable. – user2451227 Apr 22 '14 at 11:29
  • 7
    This solution is also available as an npm package: https://www.npmjs.com/package/dateformat – David Oct 21 '15 at 15:29
  • 4
    If you're going to the trouble of importing a external dependency, I'd recommend using moment.js. It can do this type of date formatting: https://momentjs.com/docs/#/displaying/ And it has much more functionality. – Drew Dara-Abrams Jul 06 '18 at 21:31
  • timezone also works well for dateformat compared to [Date API](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleDateString) in IE – Sandeep Kumar Aug 29 '18 at 22:19
614

If you need to quickly format your date using plain JavaScript, use getDate, getMonth + 1, getFullYear, getHours and getMinutes:

var d = new Date();

var datestring = d.getDate()  + "-" + (d.getMonth()+1) + "-" + d.getFullYear() + " " +
d.getHours() + ":" + d.getMinutes();

// 16-5-2015 9:50

Or, if you need it to be padded with zeros:

var datestring = ("0" + d.getDate()).slice(-2) + "-" + ("0"+(d.getMonth()+1)).slice(-2) + "-" +
    d.getFullYear() + " " + ("0" + d.getHours()).slice(-2) + ":" + ("0" + d.getMinutes()).slice(-2);

// 16-05-2015 09:50
lorem monkey
  • 3,712
  • 3
  • 32
  • 47
sebastian.i
  • 6,267
  • 1
  • 8
  • 7
459

Well, what I wanted was to convert today's date to a MySQL friendly date string like 2012-06-23, and to use that string as a parameter in one of my queries. The simple solution I've found is this:

var today = new Date().toISOString().slice(0, 10);

Keep in mind that the above solution does not take into account your timezone offset.

You might consider using this function instead:

function toJSONLocal (date) {
    var local = new Date(date);
    local.setMinutes(date.getMinutes() - date.getTimezoneOffset());
    return local.toJSON().slice(0, 10);
}

This will give you the correct date in case you are executing this code around the start/end of the day.

simo
  • 12,796
  • 7
  • 40
  • 54
  • 10
    You can do `new Date(date + " UTC")` to trick the timezone, and you can eliminate the setMinutes line. Man, javascript is dirty – Vajk Hermecz Oct 22 '15 at 22:01
  • 24
    Y10K compatible version: `var today = new Date().toISOString().slice(0,-14)` :) – Alex Shaffer Feb 25 '16 at 13:27
  • 25
    Or like this `new Date().toISOString().split('T')[0]` – rofrol Jun 02 '16 at 14:57
  • Y10K compatible and when browser doesn't returns timezone: `new Intl.DateTimeFormat('en-ca-iso8601').format(new Date())` http://stackoverflow.com/questions/6348431/best-way-to-remove-edt-from-a-date-returned-via-javascript-with-tolocalestring – rofrol Jun 02 '16 at 15:25
  • 7
    `new Date().toISOString().slice(0, 16).replace('T',' ')` to include time – Gerrie van Wyk Apr 25 '18 at 19:54
  • 4
    Just commenting that the lack of timezone is not some minor inconvenience "around the start/end of the day". In Australia, for instance, the date may be wrong until about 11AM - nearly half the day! – Steve Bennett Feb 07 '19 at 03:38
  • @slang True, but the lifespan of my program isn't Y10K compatible either :). I'll bank on there being AI to sort this out by then. – nsandersen Jul 25 '19 at 14:21
306

Custom formatting function:

For fixed formats, a simple function make the job. The following example generates the international format YYYY-MM-DD:

function dateToYMD(date) {
    var d = date.getDate();
    var m = date.getMonth() + 1; //Month from 0 to 11
    var y = date.getFullYear();
    return '' + y + '-' + (m<=9 ? '0' + m : m) + '-' + (d <= 9 ? '0' + d : d);
}

console.log(dateToYMD(new Date(2017,10,5))); // Nov 5

The OP format may be generated like:

function dateToYMD(date) {
    var strArray=['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
    var d = date.getDate();
    var m = strArray[date.getMonth()];
    var y = date.getFullYear();
    return '' + (d <= 9 ? '0' + d : d) + '-' + m + '-' + y;
}
console.log(dateToYMD(new Date(2017,10,5))); // Nov 5

Note: It is, however, usually not a good idea to extend the JavaScript standard libraries (e.g. by adding this function to the prototype of Date).

A more advanced function could generate configurable output based on a format parameter.

If to write a formatting function is too long, there are plenty of libraries around which does it. Some other answers already enumerate them. But increasing dependencies also has it counter-part.

Standard ECMAScript formatting functions:

Since more recent versions of ECMAScript, the Date class has some specific formatting functions:

toDateString: Implementation dependent, show only the date.

https://262.ecma-international.org/#sec-date.prototype.todatestring

new Date().toDateString(); // e.g. "Fri Nov 11 2016"

toISOString: Show ISO 8601 date and time.

https://262.ecma-international.org/#sec-date.prototype.toisostring

new Date().toISOString(); // e.g. "2016-11-21T08:00:00.000Z"

toJSON: Stringifier for JSON.

https://262.ecma-international.org/#sec-date.prototype.tojson

new Date().toJSON(); // e.g. "2016-11-21T08:00:00.000Z"

toLocaleDateString: Implementation dependent, a date in locale format.

https://262.ecma-international.org/#sec-date.prototype.tolocaledatestring

new Date().toLocaleDateString(); // e.g. "21/11/2016"

toLocaleString: Implementation dependent, a date&time in locale format.

https://262.ecma-international.org/#sec-date.prototype.tolocalestring

new Date().toLocaleString(); // e.g. "21/11/2016, 08:00:00 AM"

toLocaleTimeString: Implementation dependent, a time in locale format.

https://262.ecma-international.org/#sec-date.prototype.tolocaletimestring

new Date().toLocaleTimeString(); // e.g. "08:00:00 AM"

toString: Generic toString for Date.

https://262.ecma-international.org/#sec-date.prototype.tostring

new Date().toString(); // e.g. "Fri Nov 21 2016 08:00:00 GMT+0100 (W. Europe Standard Time)"

Note: it is possible to generate custom output out of those formatting >

new Date().toISOString().slice(0,10); //return YYYY-MM-DD

Examples snippets:

console.log("1) "+  new Date().toDateString());
console.log("2) "+  new Date().toISOString());
console.log("3) "+  new Date().toJSON());
console.log("4) "+  new Date().toLocaleDateString());
console.log("5) "+  new Date().toLocaleString());
console.log("6) "+  new Date().toLocaleTimeString());
console.log("7) "+  new Date().toString());
console.log("8) "+  new Date().toISOString().slice(0,10));

Specifying the locale for standard functions:

Some of the standard functions listed above are dependent on the locale:

  • toLocaleDateString()
  • toLocaleTimeString()
  • toLocalString()

This is because different cultures make uses of different formats, and express their date or time in different ways. The function by default will return the format configured on the device it runs, but this can be specified by setting the arguments (ECMA-402).

toLocaleDateString([locales[, options]])
toLocaleTimeString([locales[, options]])
toLocaleString([locales[, options]])
//e.g. toLocaleDateString('ko-KR');

The option second parameter, allow for configuring more specific format inside the selected locale. For instance, the month can be show as full-text or abreviation.

toLocaleString('en-GB', { month: 'short' })
toLocaleString('en-GB', { month: 'long' })

Examples snippets:

console.log("1) "+  new Date().toLocaleString('en-US'));
console.log("2) "+  new Date().toLocaleString('ko-KR'));
console.log("3) "+  new Date().toLocaleString('de-CH'));

console.log("4) "+  new Date().toLocaleString('en-GB', { hour12: false }));
console.log("5) "+  new Date().toLocaleString('en-GB', { hour12: true }));

Some good practices regarding locales:

  • Most people don't like their dates to appear in a foreigner format, consequently, keep the default locale whenever possible (over setting 'en-US' everywhere).
  • Implementing conversion from/to UTC can be challenging (considering DST, time-zone not multiple of 1 hour, etc.). Use a well-tested library when possible.
  • Don't assume the locale correlate to a country: several countries have many of them (Canada, India, etc.)
  • Avoid detecting the locale through non-standard ways. Here you can read about the multiple pitfalls: detecting the keyboard layout, detecting the locale by the geographic location, etc..
ino
  • 1,698
  • 1
  • 12
  • 21
Adrian Maire
  • 11,506
  • 8
  • 34
  • 72
183

If you are already using jQuery UI in your project you could do it this way:

var formatted = $.datepicker.formatDate("M d, yy", new Date("2014-07-08T09:02:21.377"));

// formatted will be 'Jul 8, 2014'

Some datepicker date format options to play with are available here.

Dmitry Pavlov
  • 25,557
  • 8
  • 92
  • 105
146

I think you can just use the non-standard Date method toLocaleFormat(formatString)

formatString: A format string in the same format expected by the strftime() function in C.

var today = new Date();
today.toLocaleFormat('%d-%b-%Y'); // 30-Dec-2011

References:

Slava Fomin II
  • 21,036
  • 19
  • 98
  • 176
Sébastien
  • 1,757
  • 1
  • 10
  • 3
  • 169
    toLocaleFormat() appears to only work in Firefox. Both IE and Chrome are failing for me. – fitzgeraldsteele Jun 11 '12 at 21:02
  • 16
    Chrome has .toLocaleString('en') method. As it seems new browser supports this https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleString – apocalypz Jul 09 '14 at 12:44
  • 8
    Read warning here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleFormat – Carson Reinke Feb 09 '15 at 20:09
  • 2
    `new Intl.DateTimeFormat` appears to be the replacement https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DateTimeFormat – Josh Unger Dec 20 '16 at 23:19
  • 2
    7 years later this function still does not work in other browsers and was deprecated in Firefox [Deprecated_toLocaleFormat](https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Fehler/Deprecated_toLocaleFormat) – Manuel Ortiz Aug 08 '18 at 18:12
  • 1
    `toLocaleString()` should be used instead: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleString – Marco Roy Dec 10 '19 at 01:50
  • Property 'toLocaleFormat' does not exist on type 'Date'. – Filipe Madureira Jul 01 '20 at 08:14
113

Plain JavaScript is the best pick for small onetimers.

On the other hand, if you need more date stuff, MomentJS is a great solution.

For example:

moment().format('YYYY-MM-DD HH:m:s');     // now() -> 2015-03-24 14:32:20
moment("20111031", "YYYYMMDD").fromNow(); // 3 years ago
moment("20120620", "YYYYMMDD").fromNow(); // 3 years ago
moment().startOf('day').fromNow();        // 11 hours ago
moment().endOf('day').fromNow();          // in 13 hours
Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
Mite Mitreski
  • 3,462
  • 3
  • 25
  • 38
  • 2
    important to mention: don't use `YYYY` unless you know the difference between `YYYY` and `yyyy`: https://stackoverflow.com/questions/15133549/difference-between-yyyy-and-yyyy-in-nsdateformatter – Domin Jan 06 '20 at 14:46
  • @Domin that's specific to NSDateFormatter in iOS, as used from e.g. Objective-C or Swift. This question is about Javascript in the browser, and this answer uses MomentJS, in which `YYYY` (not `yyyy`) is the standard year and `GGGG` (not `YYYY`) is the ISO week-based year. – Mark Reed Mar 04 '20 at 13:05
106

In modern browsers (*), you can just do this:

var today = new Date().toLocaleDateString('en-GB', {
    day : 'numeric',
    month : 'short',
    year : 'numeric'
}).split(' ').join('-');

Output if executed today (january 24ᵗʰ, 2016):

'24-Jan-2016'

(*) According to MDN, "modern browsers" means Chrome 24+, Firefox 29+, Internet Explorer 11, Edge 12+, Opera 15+ & Safari nightly build.

John Slegers
  • 38,420
  • 17
  • 182
  • 152
56

Requested format in one line - no libraries and no Date methods, just regex:

var d = (new Date()).toString().replace(/\S+\s(\S+)\s(\d+)\s(\d+)\s.*/,'$2-$1-$3');
// date will be formatted as "14-Oct-2015" (pass any date object in place of 'new Date()')

In my testing, this works reliably in the major browsers (Chrome, Safari, Firefox and IE.) As @RobG pointed out, the output of Date.prototype.toString() is implementation-dependent, so for international or non-browser implementations, just test the output to be sure it works right in your JavaScript engine. You can even add some code to test the string output and make sure it's matching what you expect before you do the regex replace.

JD Smith
  • 1,704
  • 15
  • 15
41

@Sébastien -- alternative all browser support

new Date(parseInt(496407600)*1000).toLocaleDateString('de-DE', {
year: 'numeric',
month: '2-digit',
day: '2-digit'
}).replace(/\./g, '/');

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


High-order tagged template literal example based on Date.toLocaleDateString:

const date = new Date(Date.UTC(2020, 4, 2, 3, 23, 16, 738));
const fmt = (dt, lc = "en-US") => (str, ...expr) =>
    str.map((str, i) => str + (expr[i]?dt.toLocaleDateString(lc, expr[i]) :'')).join('')

console.log(fmt(date)`${{year: 'numeric'}}-${{month: '2-digit'}}-${{day: '2-digit'}}`);
// expected output: "2020-05-02"
hakre
  • 178,314
  • 47
  • 389
  • 754
user956584
  • 4,532
  • 2
  • 34
  • 46
38

OK, we have got something called Intl which is very useful for formatting a date in JavaScript these days:

Your date as below:

var date = '10/8/2010';

And you change to Date by using new Date() like below:

date = new Date(date);

And now you can format it any way you like using a list of locales like below:

date = new Intl.DateTimeFormat('en-AU').format(date); // Australian date format: "8/10/2010" 


date = new Intl.DateTimeFormat('en-US').format(date); // USA date format: "10/8/2010" 


date = new Intl.DateTimeFormat('ar-EG').format(date);  // Arabic date format: "٨‏/١٠‏/٢٠١٠"

If you exactly want the format you mentioned above, you can do:

date = new Date(Date.UTC(2010, 7, 10, 0, 0, 0));
var options = {year: "numeric", month: "short", day: "numeric"};
date = new Intl.DateTimeFormat("en-AU", options).format(date).replace(/\s/g, '-');

And the result is going to be:

"10-Aug-2010"

For more see the Intl API and Intl.DateTimeFormat documentation.

robsiemb
  • 4,959
  • 7
  • 24
  • 33
Alireza
  • 83,698
  • 19
  • 241
  • 152
  • Not supported by IE – Pants Aug 10 '19 at 12:29
  • It is but only by IE11, IE10- have been out of life way before this existed so it's understandable. 92% from caniuse, which is pretty good https://caniuse.com/#search=datetimeformat – Tofandel Jan 08 '20 at 20:19
38

Packaged Solution: Luxon

If you want to use a one solution to fit all, I highly recommend using Luxon (a modernized version of Moment.js) which also does formatting in many locales/languages and tons of other features.

Luxon is hosted on the Moment.js website and developed by a Moment.js developer because Moment.js has limitations that the developer wanted to address but couldn't.

To install:

npm install luxon or yarn add luxon (visit link for other installation methods)

Example:

luxon.DateTime.fromISO('2010-08-10').toFormat('yyyy-LLL-dd');

Yields:

10-Aug-2010

Manual Solution

Using similar formatting as Moment.js, Class DateTimeFormatter (Java), and Class SimpleDateFormat (Java), I implemented a comprehensive solution formatDate(date, patternStr) where the code is easy to read and modify. You can display date, time, AM/PM, etc. See code for more examples.

Example:

formatDate(new Date(), 'EEEE, MMMM d, yyyy HH:mm:ss:S')

(formatDate is implemented in the code snippet below)

Yields:

Friday, October 12, 2018 18:11:23:445

Try the code out by clicking "Run code snippet."

Date and Time Patterns

yy = 2-digit year; yyyy = full year

M = digit month; MM = 2-digit month; MMM = short month name; MMMM = full month name

EEEE = full weekday name; EEE = short weekday name

d = digit day; dd = 2-digit day

h = hours am/pm; hh = 2-digit hours am/pm; H = hours; HH = 2-digit hours

m = minutes; mm = 2-digit minutes; aaa = AM/PM

s = seconds; ss = 2-digit seconds

S = miliseconds

var monthNames = [
  "January", "February", "March", "April", "May", "June", "July",
  "August", "September", "October", "November", "December"
];
var dayOfWeekNames = [
  "Sunday", "Monday", "Tuesday",
  "Wednesday", "Thursday", "Friday", "Saturday"
];
function formatDate(date, patternStr){
    if (!patternStr) {
        patternStr = 'M/d/yyyy';
    }
    var day = date.getDate(),
        month = date.getMonth(),
        year = date.getFullYear(),
        hour = date.getHours(),
        minute = date.getMinutes(),
        second = date.getSeconds(),
        miliseconds = date.getMilliseconds(),
        h = hour % 12,
        hh = twoDigitPad(h),
        HH = twoDigitPad(hour),
        mm = twoDigitPad(minute),
        ss = twoDigitPad(second),
        aaa = hour < 12 ? 'AM' : 'PM',
        EEEE = dayOfWeekNames[date.getDay()],
        EEE = EEEE.substr(0, 3),
        dd = twoDigitPad(day),
        M = month + 1,
        MM = twoDigitPad(M),
        MMMM = monthNames[month],
        MMM = MMMM.substr(0, 3),
        yyyy = year + "",
        yy = yyyy.substr(2, 2)
    ;
    // checks to see if month name will be used
    patternStr = patternStr
      .replace('hh', hh).replace('h', h)
      .replace('HH', HH).replace('H', hour)
      .replace('mm', mm).replace('m', minute)
      .replace('ss', ss).replace('s', second)
      .replace('S', miliseconds)
      .replace('dd', dd).replace('d', day)
      
      .replace('EEEE', EEEE).replace('EEE', EEE)
      .replace('yyyy', yyyy)
      .replace('yy', yy)
      .replace('aaa', aaa);
    if (patternStr.indexOf('MMM') > -1) {
        patternStr = patternStr
          .replace('MMMM', MMMM)
          .replace('MMM', MMM);
    }
    else {
        patternStr = patternStr
          .replace('MM', MM)
          .replace('M', M);
    }
    return patternStr;
}
function twoDigitPad(num) {
    return num < 10 ? "0" + num : num;
}
console.log(formatDate(new Date()));
console.log(formatDate(new Date(), 'dd-MMM-yyyy')); //OP's request
console.log(formatDate(new Date(), 'EEEE, MMMM d, yyyy HH:mm:ss.S aaa'));
console.log(formatDate(new Date(), 'EEE, MMM d, yyyy HH:mm'));
console.log(formatDate(new Date(), 'yyyy-MM-dd HH:mm:ss.S'));
console.log(formatDate(new Date(), 'M/dd/yyyy h:mmaaa'));

Thank you @Gerry for bringing up Luxon.

lewdev
  • 5,351
  • 1
  • 22
  • 20
34

Using an ECMAScript Edition 6 (ES6/ES2015) string template:

let d = new Date();
let formatted = `${d.getFullYear()}-${d.getMonth() + 1}-${d.getDate()}`;

If you need to change the delimiters:

const delimiter = '/';
let formatted = [d.getFullYear(), d.getMonth() + 1, d.getDate()].join(delimiter);
vdegenne
  • 8,291
  • 10
  • 65
  • 90
21

A JavaScript solution without using any external libraries:

var now = new Date()
months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
var formattedDate = now.getDate() + "-" + months[now.getMonth()] + "-" + now.getFullYear()
alert(formattedDate)
Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
Prasad DLV
  • 390
  • 2
  • 9
20

Here's is some code I just wrote to handle the date formatting for a project I'm working on. It mimics the PHP date formatting functionality to suit my needs. Feel free to use it, it's just extending the already existing Date() object. This may not be the most elegant solution but it's working for my needs.

var d = new Date(); 
d_string = d.format("m/d/Y h:i:s");

/**************************************
 * Date class extension
 * 
 */
    // Provide month names
    Date.prototype.getMonthName = function(){
        var month_names = [
                            'January',
                            'February',
                            'March',
                            'April',
                            'May',
                            'June',
                            'July',
                            'August',
                            'September',
                            'October',
                            'November',
                            'December'
                        ];

        return month_names[this.getMonth()];
    }

    // Provide month abbreviation
    Date.prototype.getMonthAbbr = function(){
        var month_abbrs = [
                            'Jan',
                            'Feb',
                            'Mar',
                            'Apr',
                            'May',
                            'Jun',
                            'Jul',
                            'Aug',
                            'Sep',
                            'Oct',
                            'Nov',
                            'Dec'
                        ];

        return month_abbrs[this.getMonth()];
    }

    // Provide full day of week name
    Date.prototype.getDayFull = function(){
        var days_full = [
                            'Sunday',
                            'Monday',
                            'Tuesday',
                            'Wednesday',
                            'Thursday',
                            'Friday',
                            'Saturday'
                        ];
        return days_full[this.getDay()];
    };

    // Provide full day of week name
    Date.prototype.getDayAbbr = function(){
        var days_abbr = [
                            'Sun',
                            'Mon',
                            'Tue',
                            'Wed',
                            'Thur',
                            'Fri',
                            'Sat'
                        ];
        return days_abbr[this.getDay()];
    };

    // Provide the day of year 1-365
    Date.prototype.getDayOfYear = function() {
        var onejan = new Date(this.getFullYear(),0,1);
        return Math.ceil((this - onejan) / 86400000);
    };

    // Provide the day suffix (st,nd,rd,th)
    Date.prototype.getDaySuffix = function() {
        var d = this.getDate();
        var sfx = ["th","st","nd","rd"];
        var val = d%100;

        return (sfx[(val-20)%10] || sfx[val] || sfx[0]);
    };

    // Provide Week of Year
    Date.prototype.getWeekOfYear = function() {
        var onejan = new Date(this.getFullYear(),0,1);
        return Math.ceil((((this - onejan) / 86400000) + onejan.getDay()+1)/7);
    } 

    // Provide if it is a leap year or not
    Date.prototype.isLeapYear = function(){
        var yr = this.getFullYear();

        if ((parseInt(yr)%4) == 0){
            if (parseInt(yr)%100 == 0){
                if (parseInt(yr)%400 != 0){
                    return false;
                }
                if (parseInt(yr)%400 == 0){
                    return true;
                }
            }
            if (parseInt(yr)%100 != 0){
                return true;
            }
        }
        if ((parseInt(yr)%4) != 0){
            return false;
        } 
    };

    // Provide Number of Days in a given month
    Date.prototype.getMonthDayCount = function() {
        var month_day_counts = [
                                    31,
                                    this.isLeapYear() ? 29 : 28,
                                    31,
                                    30,
                                    31,
                                    30,
                                    31,
                                    31,
                                    30,
                                    31,
                                    30,
                                    31
                                ];

        return month_day_counts[this.getMonth()];
    } 

    // format provided date into this.format format
    Date.prototype.format = function(dateFormat){
        // break apart format string into array of characters
        dateFormat = dateFormat.split("");

        var date = this.getDate(),
            month = this.getMonth(),
            hours = this.getHours(),
            minutes = this.getMinutes(),
            seconds = this.getSeconds();
        // get all date properties ( based on PHP date object functionality )
        var date_props = {
            d: date < 10 ? '0'+date : date,
            D: this.getDayAbbr(),
            j: this.getDate(),
            l: this.getDayFull(),
            S: this.getDaySuffix(),
            w: this.getDay(),
            z: this.getDayOfYear(),
            W: this.getWeekOfYear(),
            F: this.getMonthName(),
            m: month < 10 ? '0'+(month+1) : month+1,
            M: this.getMonthAbbr(),
            n: month+1,
            t: this.getMonthDayCount(),
            L: this.isLeapYear() ? '1' : '0',
            Y: this.getFullYear(),
            y: this.getFullYear()+''.substring(2,4),
            a: hours > 12 ? 'pm' : 'am',
            A: hours > 12 ? 'PM' : 'AM',
            g: hours % 12 > 0 ? hours % 12 : 12,
            G: hours > 0 ? hours : "12",
            h: hours % 12 > 0 ? hours % 12 : 12,
            H: hours,
            i: minutes < 10 ? '0' + minutes : minutes,
            s: seconds < 10 ? '0' + seconds : seconds           
        };

        // loop through format array of characters and add matching data else add the format character (:,/, etc.)
        var date_string = "";
        for(var i=0;i<dateFormat.length;i++){
            var f = dateFormat[i];
            if(f.match(/[a-zA-Z]/g)){
                date_string += date_props[f] ? date_props[f] : '';
            } else {
                date_string += f;
            }
        }

        return date_string;
    };
/*
 *
 * END - Date class extension
 * 
 ************************************/
jmiraglia
  • 573
  • 3
  • 10
18

A useful and flexible way for formatting the DateTimes in JavaScript is Intl.DateTimeFormat:

var date = new Date();
var options = { year: 'numeric', month: 'short', day: '2-digit'};
var _resultDate = new Intl.DateTimeFormat('en-GB', options).format(date);
// The _resultDate is: "12 Oct 2017"
// Replace all spaces with - and then log it.
console.log(_resultDate.replace(/ /g,'-'));

Result Is: "12-Oct-2017"

The date and time formats can be customized using the options argument.

The Intl.DateTimeFormat object is a constructor for objects that enable language sensitive date and time formatting.

Syntax

new Intl.DateTimeFormat([locales[, options]])
Intl.DateTimeFormat.call(this[, locales[, options]])

Parameters

locales

Optional. A string with a BCP 47 language tag, or an array of such strings. For the general form and interpretation of the locales argument, see the Intl page. The following Unicode extension keys are allowed:

nu
Numbering system. Possible values include: "arab", "arabext", "bali", "beng", "deva", "fullwide", "gujr", "guru", "hanidec", "khmr", "knda", "laoo", "latn", "limb", "mlym", "mong", "mymr", "orya", "tamldec", "telu", "thai", "tibt".
ca
Calendar. Possible values include: "buddhist", "chinese", "coptic", "ethioaa", "ethiopic", "gregory", "hebrew", "indian", "islamic", "islamicc", "iso8601", "japanese", "persian", "roc".

Options

Optional. An object with some or all of the following properties:

localeMatcher

The locale matching algorithm to use. Possible values are "lookup" and "best fit"; the default is "best fit". For information about this option, see the Intl page.

timeZone

The time zone to use. The only value implementations must recognize is "UTC"; the default is the runtime's default time zone. Implementations may also recognize the time zone names of the IANA time zone database, such as "Asia/Shanghai", "Asia/Kolkata", "America/New_York".

hour12

Whether to use 12-hour time (as opposed to 24-hour time). Possible values are true and false; the default is locale dependent.

formatMatcher

The format matching algorithm to use. Possible values are "basic" and "best fit"; the default is "best fit". See the following paragraphs for information about the use of this property.

The following properties describe the date-time components to use in formatted output and their desired representations. Implementations are required to support at least the following subsets:

weekday, year, month, day, hour, minute, second
weekday, year, month, day
year, month, day
year, month
month, day
hour, minute, second
hour, minute

Implementations may support other subsets, and requests will be negotiated against all available subset-representation combinations to find the best match. Two algorithms are available for this negotiation and selected by the formatMatcher property: A fully specified "basic" algorithm and an implementation dependent "best fit" algorithm.

weekday

The representation of the weekday. Possible values are "narrow", "short", "long".

era

The representation of the era. Possible values are "narrow", "short", "long".

year

The representation of the year. Possible values are "numeric", "2-digit".

month

The representation of the month. Possible values are "numeric", "2-digit", "narrow", "short", "long".

day

The representation of the day. Possible values are "numeric", "2-digit".

hour

The representation of the hour. Possible values are "numeric", "2-digit".

minute

The representation of the minute. Possible values are "numeric", "2-digit".

second

The representation of the second. Possible values are "numeric", "2-digit".

timeZoneName

The representation of the time zone name. Possible values are "short", "long". The default value for each date-time component property is undefined, but if all component properties are undefined, then the year, month and day are assumed to be "numeric".

Check Online

More Details

Iman Bahrampour
  • 4,608
  • 2
  • 32
  • 57
18

new Date().toLocaleDateString()

// "3/21/2018"

More documentation at developer.mozilla.org

Kirk Strobeck
  • 15,873
  • 14
  • 70
  • 107
16

We have lots of solutions for this, but I think the best of them is Moment.js. So I personally suggest to use Moment.js for date and time operations.

console.log(moment().format('DD-MMM-YYYY'));
<script src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.14.1/moment.min.js"></script>
Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
Vijay Maheriya
  • 1,449
  • 14
  • 21
16

This may help with the problem:

var d = new Date();

var options = {   
    day: 'numeric',
    month: 'long', 
    year: 'numeric'
};

console.log(d.toLocaleDateString('en-ZA', options));

Date to locate format

Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
Mr Nsubuga
  • 212
  • 2
  • 7
15

If you are using jQuery UI in your code, there is an inbuilt function called formatDate(). I am using it this way to format today's date:

var testdate = Date();
testdate = $.datepicker.formatDate( "d-M-yy",new Date(testdate));
alert(testdate);

You can see many other examples of formatting date in the jQuery UI documentation.

Carrie Kendall
  • 10,761
  • 5
  • 57
  • 79
webzy
  • 296
  • 2
  • 11
14

This is how I implemented for my npm plugins

var monthNames = [
  "January", "February", "March",
  "April", "May", "June", "July",
  "August", "September", "October",
  "November", "December"
];

var Days = [
  "Sunday", "Monday", "Tuesday", "Wednesday",
  "Thursday", "Friday", "Saturday"
];

var formatDate = function(dt,format){
  format = format.replace('ss', pad(dt.getSeconds(),2));
  format = format.replace('s', dt.getSeconds());
  format = format.replace('dd', pad(dt.getDate(),2));
  format = format.replace('d', dt.getDate());
  format = format.replace('mm', pad(dt.getMinutes(),2));
  format = format.replace('m', dt.getMinutes());
  format = format.replace('MMMM', monthNames[dt.getMonth()]);
  format = format.replace('MMM', monthNames[dt.getMonth()].substring(0,3));
  format = format.replace('MM', pad(dt.getMonth()+1,2));
  format = format.replace(/M(?![ao])/, dt.getMonth()+1);
  format = format.replace('DD', Days[dt.getDay()]);
  format = format.replace(/D(?!e)/, Days[dt.getDay()].substring(0,3));
  format = format.replace('yyyy', dt.getFullYear());
  format = format.replace('YYYY', dt.getFullYear());
  format = format.replace('yy', (dt.getFullYear()+"").substring(2));
  format = format.replace('YY', (dt.getFullYear()+"").substring(2));
  format = format.replace('HH', pad(dt.getHours(),2));
  format = format.replace('H', dt.getHours());
  return format;
}

pad = function(n, width, z) {
  z = z || '0';
  n = n + '';
  return n.length >= width ? n : new Array(width - n.length + 1).join(z) + n;
}
Amit Kumar Gupta
  • 6,271
  • 11
  • 54
  • 77
  • Which package are you referring to? – lbrahim Nov 02 '16 at 08:11
  • This has a bug: Month names are replaced first, then the name of the month will be replaced as well. For example `March` will become `3arch` with this code. – ntaso Feb 22 '17 at 09:41
  • 1
    Change line for `'M'` to `format = format.replace("M(?!M)", (dt.getMonth()+1).toString());` and put it above line with `'MMMM'` – ntaso Feb 22 '17 at 09:46
13

You should have a look at DayJs It's a remake of momentJs but modular architecture oriented so lighter.

Fast 2kB alternative to Moment.js with the same modern API

Day.js is a minimalist JavaScript library that parses, validates, manipulates, and displays dates and times for modern browsers with a largely Moment.js-compatible API. If you use Moment.js, you already know how to use Day.js.

var date = Date.now();
const formatedDate = dayjs(date).format("YYYY-MM-DD")
console.log(formatedDate);
<script src="https://cdnjs.cloudflare.com/ajax/libs/dayjs/1.8.16/dayjs.min.js" crossorigin="anonymous"></script>
Melchia
  • 16,699
  • 16
  • 70
  • 93
10
var today = new Date();
var formattedToday = today.toLocaleDateString() + ' ' + today.toLocaleTimeString();
Jeffrey Knight
  • 5,689
  • 5
  • 36
  • 46
Gennadiy Ryabkin
  • 6,364
  • 3
  • 28
  • 37
10

Inspired by JD Smith's marvellous regular expression solution, I suddenly had this head-splitting idea:

var D = Date().toString().split(" ");
console.log(D[2] + "-" + D[1] + "-" + D[3]);
Kamil Kiełczewski
  • 53,729
  • 20
  • 259
  • 241
Dave
  • 2,449
  • 26
  • 30
9

For any one looking for a really simple ES6 solution to copy, paste and adopt:

const dateToString = d => `${d.getFullYear()}-${('00' + (d.getMonth() + 1)).slice(-2)}-${('00' + d.getDate()).slice(-2)}` 

// how to use:
const myDate = new Date(Date.parse('04 Dec 1995 00:12:00 GMT'))
console.log(dateToString(myDate)) // 1995-12-04
Hinrich
  • 11,828
  • 4
  • 37
  • 54
  • Small improvement: to ensure a two digit result, this works fine: `('0' + oneOrTwoDigitNumber).slice(-2)`. There is no need to use `('00' + oneOrTwoDigitNumber).slice(-2)` because we know that oneOrTwoDigitNumber is at least one digit in length. – David J. Jul 09 '20 at 05:13
9

As of 2019, it looks like you can get toLocaleDateString to return only certain parts and then you can join them as you wish:

var date = new Date();

console.log(date.toLocaleDateString("en-US", { day: 'numeric' }) 
            + "-"+ date.toLocaleDateString("en-US", { month: 'short' })
            + "-" + date.toLocaleDateString("en-US", { year: 'numeric' }) );

> 16-Nov-2019

console.log(date.toLocaleDateString("en-US", { month: 'long' }) 
            + " " + date.toLocaleDateString("en-US", { day: 'numeric' }) 
            + ", " + date.toLocaleDateString("en-US", { year: 'numeric' }) );

> November 16, 2019
K Vij
  • 895
  • 8
  • 13
9

In order to format a date as e.g. 10-Aug-2010, you might want to use .toDateString() and ES6 array destructuring.

const formattedDate = new Date().toDateString()
// The above yields e.g. 'Mon Jan 06 2020'

const [, month, day, year] = formattedDate.split(' ')

const ddMmmYyyy = `${day}-${month}-${year}`
// or
const ddMmmYyyy = [day, month, year].join('-')
Chris Kobrzak
  • 738
  • 9
  • 16
8

Sugar.js has excellent extensions to the Date object, including a Date.format method.

Examples from the documentation:

Date.create().format('{Weekday} {Month} {dd}, {yyyy}');

Date.create().format('{12hr}:{mm}{tt}')
Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
hasen
  • 148,751
  • 62
  • 182
  • 223
7

To obtain "10-Aug-2010", try:

var date = new Date('2010-08-10 00:00:00');
date = date.toLocaleDateString(undefined, {day:'2-digit'}) + '-' + date.toLocaleDateString(undefined, {month:'short'}) + '-' + date.toLocaleDateString(undefined, {year:'numeric'})

For browser support, see toLocaleDateString.

Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
site
  • 800
  • 6
  • 11
  • I did not need a "-", here is a shorter version with time, date and time zone! date=new Date(); date.toLocaleDateString(undefined, {day:'2-digit', month: 'short', year: 'numeric', hour: 'numeric', minute: 'numeric', timeZoneName: 'short'}); :) – varun Sep 01 '19 at 17:06
5

Try this:

function init(){
    var d = new Date();
    var day = d.getDate();
    var x = d.toDateString().substr(4, 3);
    var year = d.getFullYear();
    document.querySelector("#mydate").innerHTML = day + '-' + x + '-' + year;
}
window.onload = init;
<div id="mydate"></div>
Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
Arjun Nayak
  • 1,034
  • 10
  • 20
5

DateFormatter.formatDate(new Date(2010,7,10), 'DD-MMM-YYYY')

=>10-Aug-2010

DateFormatter.formatDate(new Date(), 'YYYY-MM-DD HH:mm:ss')

=>2017-11-22 19:52:37

DateFormatter.formatDate(new Date(2005, 1, 2, 3, 4, 5), 'D DD DDD DDDD, M MM MMM MMMM, YY YYYY, h hh H HH, m mm, s ss, a A')

=>2 02 Wed Wednesday, 2 02 Feb February, 05 2005, 3 03 3 03, 4 04, 5 05, am AM

var DateFormatter = {
  monthNames: [
    "January", "February", "March", "April", "May", "June",
    "July", "August", "September", "October", "November", "December"
  ],
  dayNames: ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"],
  formatDate: function (date, format) {
    var self = this;
    format = self.getProperDigits(format, /d+/gi, date.getDate());
    format = self.getProperDigits(format, /M+/g, date.getMonth() + 1);
    format = format.replace(/y+/gi, function (y) {
      var len = y.length;
      var year = date.getFullYear();
      if (len == 2)
        return (year + "").slice(-2);
      else if (len == 4)
        return year;
      return y;
    })
    format = self.getProperDigits(format, /H+/g, date.getHours());
    format = self.getProperDigits(format, /h+/g, self.getHours12(date.getHours()));
    format = self.getProperDigits(format, /m+/g, date.getMinutes());
    format = self.getProperDigits(format, /s+/gi, date.getSeconds());
    format = format.replace(/a/ig, function (a) {
      var amPm = self.getAmPm(date.getHours())
      if (a === 'A')
        return amPm.toUpperCase();
      return amPm;
    })
    format = self.getFullOr3Letters(format, /d+/gi, self.dayNames, date.getDay())
    format = self.getFullOr3Letters(format, /M+/g, self.monthNames, date.getMonth())
    return format;
  },
  getProperDigits: function (format, regex, value) {
    return format.replace(regex, function (m) {
      var length = m.length;
      if (length == 1)
        return value;
      else if (length == 2)
        return ('0' + value).slice(-2);
      return m;
    })
  },
  getHours12: function (hours) {
    // https://stackoverflow.com/questions/10556879/changing-the-1-24-hour-to-1-12-hour-for-the-gethours-method
    return (hours + 24) % 12 || 12;
  },
  getAmPm: function (hours) {
    // https://stackoverflow.com/questions/8888491/how-do-you-display-javascript-datetime-in-12-hour-am-pm-format
    return hours >= 12 ? 'pm' : 'am';
  },
  getFullOr3Letters: function (format, regex, nameArray, value) {
    return format.replace(regex, function (s) {
      var len = s.length;
      if (len == 3)
        return nameArray[value].substr(0, 3);
      else if (len == 4)
        return nameArray[value];
      return s;
    })
  }
}

console.log(DateFormatter.formatDate(new Date(), 'YYYY-MM-DD HH:mm:ss'));
console.log(DateFormatter.formatDate(new Date(), 'D DD DDD DDDD, M MM MMM MMMM, YY YYYY, h hh H HH, m mm, s ss, a A'));
console.log(DateFormatter.formatDate(new Date(2005, 1, 2, 3, 4, 5), 'D DD DDD DDDD, M MM MMM MMMM, YY YYYY, h hh H HH, m mm, s ss, a A'));

The format description was taken from Ionic Framework (it does not support Z, UTC Timezone Offset)

Not thoroughly tested

Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
amit77309
  • 5,346
  • 4
  • 18
  • 27
5

Two pure JS one-liners

In this answer I develop JD Smith idea. I was able to shorten the JD Smith regexp

let format= d=> d.toString().replace(/\w+ (\w+) (\d+) (\d+).*/,'$2-$1-$3');

console.log( format(Date()) );

Dave also base on JD Smith idea but he avoid regexp and give very nice solution - I short a little his solution (by change split param) and opaque it in wrapper

let format= (d,a=d.toString().split` `)=> a[2]+"-"+a[1]+"-"+a[3];

console.log( format(Date()) );
Kamil Kiełczewski
  • 53,729
  • 20
  • 259
  • 241
5

Works same in IE 11, FF & Chrome (Chrome 80.x shows 12 hours format when en-UK selected).

const d = new Date('2010/08/05 23:45') // 26.3.2020
const dtfUK = new Intl.DateTimeFormat('UK', { year: 'numeric', month: '2-digit', day: '2-digit',
        hour: '2-digit',minute: '2-digit', second: '2-digit' }); //
const dtfUS = new Intl.DateTimeFormat('en', { year: 'numeric', month: '2-digit', day: '2-digit',
        hour: '2-digit',minute: '2-digit', second: '2-digit' }); //
console.log(dtfUS.format(d)); // 08/05/2010 11:45:00 PM
console.log(dtfUK.format(d)); // 05.08.2010 23:45:00
/* node.js:
08/05/2010, 11:45:00 PM
2010-08-05 23:45:00
*/

What about something more general ?

var d = new Date('2010-08-10T10:34:56.789Z');
var str = d.toDateString() + // Tue Aug 10 2010
    ' ' + d.toTimeString().split(' ')[0] + // 12:34:56, GMT+0x00 (GMT+0x:00)
    ' ' + (d.getMonth() + 101) + // 108
    ' ' + d.getMilliseconds(); // 789
console.log(str); // Tue Aug 10 2010 12:34:56 108 789
console.log(//   $1 Tue  $2 Aug  $3 11     $4 2020 $5 12   $6 34   $7 56    $8 108  $9 789
    str.replace(/(\S{3}) (\S{3}) (\d{1,2}) (\d{4}) (\d{2}):(\d{2}):(\d{2}) 1(\d{2}) (\d{1,3})/, '$3-$2-$4 $5:$6.$9 ($1)')
); // 10-Aug-2010 12:34.789 (Tue)
/*
$1: Tue  Week Day string
$2: Aug  Month short text
$3: 11   Day
$4: 2010 Year
$5: 12   Hour
$6: 34   Minute
$7: 56   Seconds
$8: 08   Month
$9: 789  Milliseconds
*/

Or for example 1-line IIFE "library" ;-)

console.log(
    (function (frm, d) { return [d.toDateString(), d.toTimeString().split(' ')[0], (d.getMonth() + 101), d.getMilliseconds()].join(' ').replace(/(\S{3}) (\S{3}) (\d{1,2}) (\d{4}) (\d{2}):(\d{2}):(\d{2}) 1(\d{2}) (\d{1,3})/, frm); })
    ('$4/$8/$3 $5:$6 ($1)', new Date())
);

You can remove useless parts and / or change indexes if you do not need them.

Tom
  • 1,665
  • 3
  • 10
  • 21
4

Add the jQuery UI plugin to your page:

function DateFormate(dateFormate, datetime) {
    return $.datepicker.formatDate(dateFormate, datetime);
};
Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
Thulasiram
  • 8,044
  • 7
  • 43
  • 50
4

If you fancy a short, human-readable, function - this is easily adjustable to suit you.

The timeStamp parameter is milliseconds from 1970 - it is returned by new Date().getTime() and many other devices...

OK, I changed my mind. I included an extra function for zero padding. Curses!

 function zeroPad(aNumber) {
     return ("0"+aNumber).slice(-2);
 }
 function humanTime(timeStamp) {
    var M = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
    var D = new Date(timeStamp); // 23 Aug 2016 16:45:59 <-- Desired format.
    return D.getDate() + " " + M[D.getMonth()] + " " + D.getFullYear() + " " + D.getHours() + ":" + zeroPad(d.getMinutes()) + ":" + zeroPad(D.getSeconds());
 }
Dave
  • 2,449
  • 26
  • 30
3

I use the following. It is simple and works fine.

 var dtFormat = require('dtformat');
   var today = new Date();
   dtFormat(today, "dddd, mmmm dS, yyyy, h:MM:ss TT");

Or this:

var now = new Date()
months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
var formattedDate = now.getDate()  + "-" + months[now.getMonth()] + "-" + now.getFullYear()
alert(formattedDate)
Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
SaidB
  • 41
  • 5
3

Short, widely compatible approach:

function formatDate(date) {
    date.toISOString()
    .replace(/^(\d+)-(\d+)-(\d+).*$/, // Only extract Y-M-D
        function (a,y,m,d) {
            return [
                d, // Day
                ['Jan','Feb','Mar','Apr','May','Jun',  // Month Names
                'Jul','Ago','Sep','Oct','Nov','Dec']
                [m-1], // Month
                y  // Year
            ].join('-') // Stitch together
        })
}

Or, as a single line:

date.toISOString().replace(/^(\d+)-(\d+)-(\d+)T(\d+):(\d+):(\d+).(\d+)Z$/, function (a,y,m,d) {return [d,['Jan','Feb','Mar','Apr','May','Jun','Jul','Ago','Sep','Oct','Nov','Dic'][m-1],y].join('-')})
JP de la Torre
  • 1,311
  • 13
  • 16
2

If you are already using ExtJS in your project you could use Ext.Date:

var date = new Date();
Ext.Date.format(date, "d-M-Y");

returns:

"11-Nov-2015"
Peter
  • 8,517
  • 4
  • 37
  • 63
2

There is a new library, smarti.to.js, for localized formatting of JavaScript numbers, dates and JSON dates (Microsoft or ISO8601).

Example:

new Date('2015-1-1').to('dd.MM.yy')         // Outputs 01.01.2015
"2015-01-01T10:11:12.123Z".to('dd.MM.yy')   // Outputs 01.01.2015

There are also custom short patterns defined in the localization file (smarti.to.{culture}.js). Example (smarti.to.et-EE.js):

new Date('2015-1-1').to('d')                // Outputs 1.01.2015

And a multiformatting ability:

smarti.format('{0:n2} + {1:n2} = {2:n2}', 1, 2, 3)   // Output: 1,00 + 2,00 = 3,00
Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
Gene R
  • 3,596
  • 2
  • 16
  • 25
2

This is the main answer modified to have 3-char months, and 2-digit year:

function formatDate(date) {
    var monthNames = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
    var day = date.getDate(), monthIndex = date.getMonth(), year = date.getFullYear().toString().substr(-2);
    return day + ' ' + monthNames[monthIndex] + ' ' + year;
}

document.write(formatDate(new Date()));
Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
Basj
  • 29,668
  • 65
  • 241
  • 451
2

Other way that you can format the date:

function formatDate(dDate,sMode){
    var today = dDate;
    var dd = today.getDate();
    var mm = today.getMonth()+1; //January is 0!
    var yyyy = today.getFullYear();
    if(dd<10) {
        dd = '0'+dd
    }
    if(mm<10) {
        mm = '0'+mm
    }
    if (sMode+""==""){
        sMode = "dd/mm/yyyy";
    }
    if (sMode == "yyyy-mm-dd"){
        return  yyyy + "-" + mm + "-" + dd + "";
    }
    if (sMode == "dd/mm/yyyy"){
        return  dd + "/" + mm + "/" + yyyy;
    }
}
Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
2

yy = 2-digit year; yyyy = full year

M = digit month; MM = 2-digit month; MMM = short month name; MMMM = full month name

EEEE = full weekday name; EEE = short weekday name

d = digit day; dd = 2-digit day

h = hours; hh = 2-digit hours

m = minutes; mm = 2-digit minutes

s = seconds; ss = 2-digit seconds

S = miliseconds

Used similar formating as Class SimpleDateFormat (Java)

var monthNames = [
  "January", "February", "March", "April", "May", "June", "July",
  "August", "September", "October", "November", "December"
];
var dayOfWeekNames = [
  "Sunday", "Monday", "Tuesday",
  "Wednesday", "Thursday", "Friday", "Saturday"
];
function formatDate(date, formatStr){
    if (!formatStr) {
      formatStr = 'dd/mm/yyyy';
    }
    var day = date.getDate(),
        month = date.getMonth(),
        year = date.getFullYear(),
        hour = date.getHours(),
        minute = date.getMinutes(),
        second = date.getSeconds(),
        miliseconds = date.getMilliseconds(),
        hh = twoDigitPad(hour),
        mm = twoDigitPad(minute),
        ss = twoDigitPad(second),
        EEEE = dayOfWeekNames[date.getDay()],
        EEE = EEEE.substr(0, 3),
        dd = twoDigitPad(day),
        M = month + 1,
        MM = twoDigitPad(M),
        MMMM = monthNames[month],
        MMM = MMMM.substr(0, 3),
        yyyy = year + "",
        yy = yyyy.substr(2, 2)
    ;
    return formatStr
      .replace('hh', hh).replace('h', hour)
      .replace('mm', mm).replace('m', minute)
      .replace('ss', ss).replace('s', second)
      .replace('S', miliseconds)
      .replace('dd', dd).replace('d', day)
      .replace('MMMM', MMMM).replace('MMM', MMM).replace('MM', MM).replace('M', M)
      .replace('EEEE', EEEE).replace('EEE', EEE)
      .replace('yyyy', yyyy)
      .replace('yy', yy)
    ;
}
function twoDigitPad(num) {
    return num < 10 ? "0" + num : num;
}
console.log(formatDate(new Date()));
console.log(formatDate(new Date(), 'EEEE, MMMM d, yyyy hh:mm:ss:S'));
console.log(formatDate(new Date(), 'EEE, MMM d, yyyy hh:mm'));
console.log(formatDate(new Date(), 'yyyy-MM-dd hh:mm:ss:S'));
console.log(formatDate(new Date(), 'yy-MM-dd hh:mm'));
lewdev
  • 5,351
  • 1
  • 22
  • 20
2

This function I inspired by java's SimpleDateFormat provides various formats such as:

dd-MMM-yyyy → 17-Jul-2018
yyyyMMdd'T'HHmmssXX → 20180717T120856+0900
yyyy-MM-dd'T'HH:mm:ssXXX → 2018-07-17T12:08:56+09:00
E, dd MMM yyyy HH:mm:ss Z → Tue, 17 Jul 2018 12:08:56 +0900
yyyy.MM.dd 'at' hh:mm:ss Z → 2018.07.17 at 12:08:56 +0900
EEE, MMM d, ''yy → Tue, Jul 17, '18
h:mm a → 12:08 PM
hh 'o''''clock' a, X → 12 o'clock PM, +09

Code example:

function formatWith(formatStr, date, opts) {
    
        if (!date) {
            date = new Date();
        }
    
        opts = opts || {};
    
        let _days = opts.days;
    
        if (!_days) {
            _days = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
        }
    
        let _months = opts.months;
    
        if (!_months) {
            _months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
        }
    
        const pad = (number, strDigits, isUnpad) => {
            const strNum = number.toString();
            if (!isUnpad && strNum.length > strDigits.length) {
                return strNum;
            } else {
                return ('0000' + strNum).slice(-strDigits.length);
            }
        };
    
        const timezone = (date, letter) => {
            const chunk = [];
            const offset = -date.getTimezoneOffset();
            chunk.push(offset === 0 ? 'Z' : offset > 0 ? '+' : '-');//add Z or +,-
            if (offset === 0) return chunk;
            chunk.push(pad(Math.floor(offset / 60), '00'));//hour
            if (letter === 'X') return chunk.join('');
            if (letter === 'XXX') chunk.push(':');
            chunk.push(pad((offset % 60), '00'));//min
            return chunk.join('');
        };
    
        const ESCAPE_DELIM = '\0';
        const escapeStack = [];
    
        const escapedFmtStr = formatStr.replace(/'.*?'/g, m => {
            escapeStack.push(m.replace(/'/g, ''));
            return ESCAPE_DELIM + (escapeStack.length - 1) + ESCAPE_DELIM;
        });
    
        const formattedStr = escapedFmtStr
            .replace(/y{4}|y{2}/g, m => pad(date.getFullYear(), m, true))
            .replace(/M{3}/g, m => _months[date.getMonth()])
            .replace(/M{1,2}/g, m => pad(date.getMonth() + 1, m))
            .replace(/M{1,2}/g, m => pad(date.getMonth() + 1, m))
            .replace(/d{1,2}/g, m => pad(date.getDate(), m))
            .replace(/H{1,2}/g, m => pad(date.getHours(), m))
            .replace(/h{1,2}/g, m => {
                const hours = date.getHours();
                return pad(hours === 0 ? 12 : hours > 12 ? hours - 12 : hours, m);
            })
            .replace(/a{1,2}/g, m => date.getHours() >= 12 ? 'PM' : 'AM')
            .replace(/m{1,2}/g, m => pad(date.getMinutes(), m))
            .replace(/s{1,2}/g, m => pad(date.getSeconds(), m))
            .replace(/S{3}/g, m => pad(date.getMilliseconds(), m))
            .replace(/[E]+/g, m => _days[date.getDay()])
            .replace(/[Z]+/g, m => timezone(date, m))
            .replace(/X{1,3}/g, m => timezone(date, m))
        ;
    
        const unescapedStr = formattedStr.replace(/\0\d+\0/g, m => {
            const unescaped = escapeStack.shift();
            return unescaped.length > 0 ? unescaped : '\'';
        });
    
        return unescapedStr;
    }

    //Let's format with above function
    const dateStr = '2018/07/17 12:08:56';
    const date = new Date(dateStr);
    const patterns = [
        "dd-MMM-yyyy",
        "yyyyMMdd'T'HHmmssXX",//ISO8601
        "yyyy-MM-dd'T'HH:mm:ssXXX",//ISO8601EX
        "E, dd MMM yyyy HH:mm:ss Z",//RFC1123(RFC822) like email
        "yyyy.MM.dd 'at' hh:mm:ss Z",//hh shows 1-12
        "EEE, MMM d, ''yy",
        "h:mm a",
        "hh 'o''''clock' a, X",
    ];
    
    
    for (let pattern of patterns) {
        console.log(`${pattern} → ${formatWith(pattern, date)}`);
    }

And you can use this as a library

Also released as a NPM module.You can use this on node.js or use this from CDN for browser.

nodejs

const {SimpleDateFormat} = require('@riversun/simple-date-format');

on browser

<script src="https://cdn.jsdelivr.net/npm/@riversun/simple-date-format@1.0.2/dist/simple-date-format.js"></script>

Write code as follows.

const date = new Date('2018/07/17 12:08:56');
const sdf = new SimpleDateFormat();
console.log(sdf.formatWith("yyyy-MM-dd'T'HH:mm:ssXXX", date));//to be "2018-07-17T12:08:56+09:00"

Source code here on github:

https://github.com/riversun/simple-date-format

Dharman
  • 21,838
  • 18
  • 57
  • 107
riversun
  • 528
  • 5
  • 9
2

The Date constructor (and Date.parse()) only accepts one format as a parameter when constructing a date and that is ISO 8601:

// new Date('YYYY-MM-DDTHH:mm:ss.sssZ')
const date = new Date('2017-08-15')

But parsing a from a string is strongly discouraged (MDN recommends against creating date with date strings) due to browser differences and inconsistencies.

The recommended alternative would be building your Date instance directly from the numeric data like this:

new Date(2017, 7, 15) // month is zero-indexed

That is parsing. Now, to format your date to the string you desire you have several options that are native of the Date objet (although I believe none is compliant to the format you require):

date.toString() // gives you 'Wed Jan 23 2019 17:23:42 GMT+0800 (Singapore Standard Time)'
date.toDateString() // gives you 'Wed Jan 23 2019'
date.toLocaleString() // gives you '23/01/2019, 17:23:42'
date.toLocaleString() // gives you '23/01/2019, 17:23:42'
date.toGMTString() // gives you 'Wed, 23 Jan 2019 09:23:42 GMT'
date.toUTCString() // gives you Wed, 23 Jan 2019 09:23:42 GMT
date.toISOString() // gives you 2019-01-23T09:23:42.079Z

For other formatting options I'm afraid you'll have to turn to libraries such as moment.js, day.js and the like.

Credit to Zell Liew from this article for the date formatting tips

ppicom
  • 318
  • 2
  • 11
1

Here is a script that does exactly what you want

https://github.com/UziTech/js-date-format

var d = new Date("2010-8-10");
document.write(d.format("DD-MMM-YYYY"));
Tony Brix
  • 3,557
  • 5
  • 34
  • 46
  • 2
    Extending native prototypes is not a good idea. There are plenty of other tools out there, like Moment.js, that accomplish the same thing without touching the Date prototype. – Joe Maffei Feb 06 '19 at 21:46
1

The following code will allow you to format the date to either DD-MM-YYYY (27-12-2017) or DD MMM YYYY (27 Dec 2017) :

/** Pad number to fit into nearest power of 10 */
function padNumber(number, prependChar, count) {
  var out = '' + number; var i;
  if (number < Math.pow(10, count))
    while (out.length < ('' + Math.pow(10, count)).length) out = prependChar + out;

  return out;
}

/* Format the date to 'DD-MM-YYYY' or 'DD MMM YYYY' */
function dateToDMY(date, useNumbersOnly) {
  var months = [
    'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 
    'Nov', 'Dec'
  ];

  return '' + padNumber(date.getDate(), '0', 1) + 
   (useNumbersOnly? '-' + padNumber(date.getMonth() + 1, '0', 1) + '-' : ' ' + months[date.getMonth()] + ' ')
    + date.getFullYear();
}

Change the order of date.getFullYear() and padNumber(date.getDate(), '0', 1) to make a dateToYMD() function.

See repl.it example for details.

Agi Hammerthief
  • 1,915
  • 1
  • 19
  • 32
1

I know someone might say that this is silly solution, but it does do the trick by removing the unnecessary information from the date string.

yourDateObject produces:

Wed Dec 13 2017 20:40:40 GMT+0200 (EET)

yourDateObject.toString().slice(0, 15); produces:

Wed Dec 13 2017

Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
Combine
  • 2,868
  • 23
  • 28
1

You don't need any libraries. Just extract date components and construct the string. Here is how to get YYYY-MM-DD format. Also note the month index "January is 0, February is 1, and so on."

// @flow

type Components = {
  day: number,
  month: number,
  year: number
}

export default class DateFormatter {
  // YYYY-MM-DD
  static YYYY_MM_DD = (date: Date): string => {
    const components = DateFormatter.format(DateFormatter.components(date))
    return `${components.year}-${components.month}-${components.day}`
  }

  static format = (components: Components) => {
    return {
      day: `${components.day}`.padStart(2, '0'),
      month: `${components.month}`.padStart(2, '0'),
      year: components.year
    }
  }

  static components = (date: Date) => {
    return {
      day: date.getDate(),
      month: date.getMonth() + 1,
      year: date.getFullYear()
    }
  }
}
Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
onmyway133
  • 38,911
  • 23
  • 231
  • 237
1

A simple function that can return the date, the date + time, or just the time:

var myDate = dateFormatter("2019-01-24 11:33:24", "date-time");
// >> RETURNS "January 24, 2019 11:33:24"

var myDate2 = dateFormatter("2019-01-24 11:33:24", "date");
// >> RETURNS "January 24, 2019"

var myDate3 = dateFormatter("2019-01-24 11:33:24", "time");
// >> RETURNS "11:33:24"


function dateFormatter(strDate, format){
    var theDate = new Date(strDate);
    if (format=="time")
       return getTimeFromDate(theDate);
    else{
       var dateOptions = {year:'numeric', month:'long', day:'numeric'};
       var formattedDate = theDate.toLocaleDateString("en-US", + dateOptions);
       if (format=="date")
           return formattedDate;
       return formattedDate + " " + getTimeFromDate(theDate);
    }
}

function getTimeFromDate(theDate){
    var sec = theDate.getSeconds();
    if (sec<10)
        sec = "0" + sec;
    var min = theDate.getMinutes();
    if (min<10)
        min = "0" + min;
    return theDate.getHours() + ':'+ min + ':' + sec;
}

Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
blairzotron
  • 219
  • 2
  • 6
1

This Module can easily handle mostly every case there is. It is part of a bigger npm package, by Locutus, which includes a variety of functions, but can be used totally independent of the package it self, just copy paste/ adapt a little if not working with npm (change from module to just a function)

As a second parameter it accepts a timestamp, which can come from anywhere, such as Date.getTime()

Also, Locutus maintains a bigger datetime module, also inside the locutus package which will give a more object oriented way to use it

Here you can see other datetime functions, as modules, that proved to be very usefull too.

You can find documentation on parameters and format strings here (note that the doc site is a php site, but the locutus implementation follows exactly the same specs)

Examples of date Module

date('H:m:s \\m \\i\\s \\m\\o\\n\\t\\h', 1062402400)//'07:09:40 m is month'

date('F j, Y, g:i a', 1062462400)//'September 2, 2003, 12:26 am'

date('Y W o', 1062462400)//'2003 36 2003'

var $x = date('Y m d', (new Date()).getTime() / 1000) $x = $x + '' var $result = $x.length // 2009 01 09    10

date('W', 1104534000)   //'52'

date('B t', 1104534000) //'999 31'

date('W U', 1293750000.82); // 2010-12-31   '52 1293750000'

date('W', 1293836400); // 2011-01-01    '52'

date('W Y-m-d', 1293974054); // 2011-01-02  '52 2011-01-02'
Guilherme Ferreira
  • 1,772
  • 17
  • 21
1

function convert_month(i = 0, option = "num") { // i = index

  var object_months = [
    { num: 01, short: "Jan", long: "January" },
    { num: 02, short: "Feb", long: "Februari" }, 
    { num: 03, short: "Mar", long: "March" },          
    { num: 04, short: "Apr", long: "April" },
    { num: 05, short: "May", long: "May" },
    { num: 06, short: "Jun", long: "Juni" },
    { num: 07, short: "Jul", long: "July" },
    { num: 08, short: "Aug", long: "August" },
    { num: 09, short: "Sep", long: "September" },
    { num: 10, short: "Oct", long: "October" },
    { num: 11, short: "Nov", long: "November" },
    { num: 12, short: "Dec", long: "December" }
  ];
        
  return object_months[i][option];

}
      
var d = new Date();
      
// https://stackoverflow.com/questions/1408289/how-can-i-do-string-interpolation-in-javascript
var num   = `${d.getDate()}-${convert_month(d.getMonth())}-${d.getFullYear()}`;
var short = `${d.getDate()}-${convert_month(d.getMonth(), "short")}-${d.getFullYear()}`;
var long  = `${d.getDate()}-${convert_month(d.getMonth(), "long")}-${d.getFullYear()}`;

document.querySelector("#num").innerHTML = num;
document.querySelector("#short").innerHTML = short;
document.querySelector("#long").innerHTML = long;
<p>Numeric  : <span id="num"></span> (default)</p>
<p>Short    : <span id="short"></span></p>
<p>Long     : <span id="long"></span></p>
antelove
  • 2,039
  • 16
  • 14
0

Use:

thisDate = new Date(parseInt(jsonDateString.replace('/Date(', '')));
formattedDate = (thisDate.getMonth() + 1) + "/" + (thisDate.getDate()+1) + "/" + thisDate.getFullYear();

This takes a JSON date, "/Date(1429573751663)/" and produces as the formatted string:

"4/21/2015"

Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
pat capozzi
  • 1,294
  • 1
  • 18
  • 16
  • 3
    [There is no such thing as a JSON date](http://stackoverflow.com/questions/10286204/the-right-json-date-format). – Mark Amery Oct 31 '15 at 00:05
0

2.39KB minified. One file. https://github.com/rhroyston/clock-js

10-Aug-2010 would be:

var str = clock.month
str.charAt(0).toUpperCase() + str.slice(1,3); //gets you "Aug"
console.log(clock.day + '-' + str + '-' + clock.year); //gets you 10-Aug-2010



Ronnie Royston
  • 11,959
  • 5
  • 57
  • 72
  • 2
    Still having to do stuff like `str.charAt(0).toUpperCase() + str.slice(1,3);` kinda defeats the purpose of using a library. Why don't you add out-of-the-box support for three letter month formats? Also, you might want to consider adding internationalization to you library, as a library like this would be kinda useless for non-English websites without it! – John Slegers Jun 30 '16 at 08:25
0

Here is some ready-to-paste time/date formatting code that does NOT rely on any external modules/libraries or use jQuery or ES7 or anything. Unlike the code in some other answers, this code offers this combo of features:

  • it takes a JavaScript Date object as input
  • it can display date as local time zone or UTC
  • it uses a simple formatting system "{year4} {month02} {second}" that is easy to read and understand even after you write the code, unlike the typical "%D %m %-" which always forces you back to the documentation
  • the formatting system does not have any weird self-collisions like some ad-hoc "DD MM YYYY" systems
  • you can run the test right here and try it

// format_date(date, pattern, utc)
// - date 
//   - a JavaScript Date object
//   - use "new Date()" for current time
// - pattern
//   - a string with embedded {codes} like
//     "{year4}-{month02}-{day02}: {dayname3}"
//     see format_date_funcs below for complete list
//   - any other letters go through unchanged
// - utc
//   - if true, shows date in UTC time "zone"
//   - if false/omitted, shows date in local time zone
//
var month_names = 
[
  "January", "February", "March", "April", "May", "June", "July",
  "August", "September", "October", "November", "December"
];
var day_of_week_names = 
[
  "Sunday", "Monday", "Tuesday",
  "Wednesday", "Thursday", "Friday", "Saturday"
];
function space_pad2(num)
{
    return num < 10 ? " " + num : num;
}
function zero_pad2(num)
{
    return num < 10 ? "0" + num : num;
}
function space_pad3(num)
{
    if (num < 10) 
        return "  " + num;
    else if (num < 100)
        return " " + num;
    else
        return num;
}
function zero_pad3(num)
{
    if (num < 10) 
        return "00" + num;
    else if (num < 100)
        return "0" + num;
    else
        return num;
}
var format_date_funcs =
{
    // {year4}  = '1902'
    // {year02} =   '02'
    // 
    'year4': function(date, utc)
    {
        var year = utc ? date.getUTCFullYear() : date.getFullYear();
        return year;
    },
    'year02': function(date, utc)
    {
        var year = utc ? date.getUTCFullYear() : date.getFullYear();
        return year.toString().substr(2,2);
    },
    // {month}   =  '1' - '12'
    // {month2}  = ' 1' - '12' (space padded)
    // {month02} = '01' - '12'
    //
    'month': function(date, utc)
    {
        var month = utc ? date.getUTCMonth() : date.getMonth(); // [0,11]
        return            month + 1;
    },
    'month2': function(date, utc)
    {
        var month = utc ? date.getUTCMonth() : date.getMonth(); // [0,11]
        return space_pad2(month + 1);
    },
    'month02': function(date, utc)
    {
        var month = utc ? date.getUTCMonth() : date.getMonth(); // [0,11]
        return zero_pad2(month + 1);
    },
    // {monthname}  = 'January'
    // {monthname3} = 'Jan'
    // 
    'monthname': function(date, utc)
    {
        var month = utc ? date.getUTCMonth() : date.getMonth(); // [0,11]
        return month_names[month];
    },
    'monthname3': function(date, utc)
    {
        var month = utc ? date.getUTCMonth() : date.getMonth(); // [0,11]
        return month_names[month].substr(0, 3);
    },
    // {day}   =  '1' - '31'
    // {day2}  = ' 1' - '31' (space padded)
    // {day02} = '01' - '31'
    // 
    'day': function(date, utc)
    {
        var date = utc ? date.getUTCDate() : date.getDate(); // [1,31]
        return date;
    },
    'day2': function(date, utc)
    {
        var date = utc ? date.getUTCDate() : date.getDate(); // [1,31]
        return space_pad2(date);
    },
    'day02': function(date, utc)
    {
        var date = utc ? date.getUTCDate() : date.getDate(); // [1,31]
        return zero_pad2(date);
    },
    // {dayname}  = 'Tuesday'
    // {dayname3} = 'Tue'
    // 
    'dayname': function(date, utc)
    {
        var day = utc ? date.getUTCDay() : date.getDay(); // [0,6]
        return day_of_week_names[day];
    },
    'dayname3': function(date, utc)
    {
        var day = utc ? date.getUTCDay() : date.getDay(); // [0,6]
        return day_of_week_names[day].substr(0,3);
    },
    // {24hour}   =  '0' - '23'
    // {24hour2}  = ' 0' - '23' (space padded)
    // {24hour02} = '00' - '23'
    //
    '24hour': function(date, utc)
    {
        var hour = utc ? date.getUTCHours() : date.getHours(); // [0,23]
        return hour;
    },
    '24hour2': function(date, utc)
    {
        var hour = utc ? date.getUTCHours() : date.getHours(); // [0,23]
        return space_pad2(hour);
    },
    '24hour02': function(date, utc)
    {
        var hour = utc ? date.getUTCHours() : date.getHours(); // [0,23]
        return zero_pad2(hour);
    },
    // {12hour}   =  '1' - '12'
    // {12hour2}  = ' 1' - '12' (space padded)
    // {12hour02} = '01' - '12'
    // {ampm}     = 'am' or 'pm'
    // {AMPM}     = 'AM' or 'PM'
    //
    '12hour': function(date, utc)
    {
        var hour = utc ? date.getUTCHours() : date.getHours(); // [0,23]
        hour = hour % 12; // [0,11]
        if (0 === hour) hour = 12;
        return hour;
    },
    '12hour2': function(date, utc)
    {
        var hour = utc ? date.getUTCHours() : date.getHours(); // [0,23]
        hour = hour % 12; // [0,11]
        if (0 === hour) hour = 12;
        return space_pad2(hour);
    },
    '12hour02': function(date, utc)
    {
        var hour = utc ? date.getUTCHours() : date.getHours(); // [0,23]
        hour = hour % 12; // [0,11]
        if (0 === hour) hour = 12;
        return zero_pad2(hour);
    },
    'ampm': function(date, utc)
    {
        var hour = utc ? date.getUTCHours() : date.getHours(); // [0,23]
        return (hour < 12 ? 'am' : 'pm');
    },
    'AMPM': function(date, utc)
    {
        var hour = utc ? date.getUTCHours() : date.getHours(); // [0,23]
        return (hour < 12 ? 'AM' : 'PM');
    },
    // {minute}   =  '0' - '59'
    // {minute2}  = ' 0' - '59' (space padded)
    // {minute02} = '00' - '59'
    // 
    'minute': function(date, utc)
    {
        var minute = utc ? date.getUTCMinutes() : date.getMinutes(); // [0,59]
        return minute;
    },
    'minute2': function(date, utc)
    {
        var minute = utc ? date.getUTCMinutes() : date.getMinutes(); // [0,59]
        return space_pad2(minute);
    },
    'minute02': function(date, utc)
    {
        var minute = utc ? date.getUTCMinutes() : date.getMinutes(); // [0,59]
        return zero_pad2(minute);
    },
    // {second}   =  '0' - '59'
    // {second2}  = ' 0' - '59' (space padded)
    // {second02} = '00' - '59'
    // 
    'second': function(date, utc)
    {
        var second = utc ? date.getUTCSeconds() : date.getSeconds(); // [0,59]
        return second;
    },
    'second2': function(date, utc)
    {
        var second = utc ? date.getUTCSeconds() : date.getSeconds(); // [0,59]
        return space_pad2(second);
    },
    'second02': function(date, utc)
    {
        var second = utc ? date.getUTCSeconds() : date.getSeconds(); // [0,59]
        return zero_pad2(second);
    },
    // {msec}   =   '0' - '999'
    // {msec3}  = '  0' - '999' (space padded)
    // {msec03} = '000' - '999'
    // 
    'msec': function(date, utc)
    {
        var msec = 
            utc ? date.getUTCMilliseconds() : date.getMilliseconds(); // [0,999]
        return msec;
    },
    'msec3': function(date, utc)
    {
        var msec = 
            utc ? date.getUTCMilliseconds() : date.getMilliseconds(); // [0,999]
        return space_pad3(msec);
    },
    'msec03': function(date, utc)
    {
        var msec = 
            utc ? date.getUTCMilliseconds() : date.getMilliseconds(); // [0,999]
        return zero_pad3(msec);
    },
    // {open} = '{' (in case you actually want '{' in the output)
    //
    'open': function(date, utc)
    {
        return '{';
    }, 
    // {close} = '}' (in case you actually want '}' in the output)
    //
    'close': function(date, utc)
    {
        return '}';
    }, 
};
function format_date(date, pattern, utc)
{
    if (!pattern) 
    {
        pattern = '{month}/{day}/{year4}';
    }

    var ret = '';

    while (pattern.length > 0)
    {
        var s = pattern.indexOf('{');
        var e = pattern.indexOf('}');
        //console.log('s ' + s + ' e ' + e);
        if (-1 !== s && -1 !== e && s < e)
        {
            // - there is a well-formed {foo} in range [s,e]
            // - first we emit range [0,s) as literal
        }
        else
        {
            // - rest of string has no {} or has malformed }{ or { or }
            // - just emit the rest of the string as literal and be done
            s = pattern.length; 
        }
        // emit range [0,s) as literal
        if (s > 0)
        {
            ret += pattern.substr(0, s);
            pattern = pattern.substr(s);
            e -= s;
            s = 0;
        }

        if (0 === pattern.length) break;

        // emit range [s=0,e] by evaluating code
        console.assert(0 === s); // position of {
        console.assert(e > 0);  // position of }
        console.assert('{' === pattern.substr(s, 1));
        console.assert('}' === pattern.substr(e, 1));
        var code = pattern.substr(1,e-1);
        var func = format_date_funcs[code];
        console.assert(func);
        ret += func(date, utc);

        pattern = pattern.substr(e+1);
    }

    return ret;
}

if (1) // test format_date
{
    var fmt = '[';
    for (var func in format_date_funcs) 
    {
        if (!format_date_funcs.hasOwnProperty(func)) continue;
        fmt += '{' + func + '}/';
    }
    fmt += ']';
    var now = new Date();
    console.log(fmt);
    console.log(format_date(now, fmt, false /*utc*/));
    console.log(format_date(now, fmt, true /*utc*/));
}
Louis Semprini
  • 2,495
  • 25
  • 26
0

May be this helps some one who are looking for multiple date formats one after the other by willingly or unexpectedly. Please find the code: I am using moment.js format function on a current date as (today is 29-06-2020) var startDate = moment(new Date()).format('MM/DD/YY'); Result: 06/28/20

what happening is it retains only the year part :20 as "06/28/20", after If I run the statement : new Date(startDate) The result is "Mon Jun 28 1920 00:00:00 GMT+0530 (India Standard Time)",

Then, when I use another format on "06/28/20": startDate = moment(startDate ).format('MM-DD-YYYY'); Result: 06-28-1920, in google chrome and firefox browsers it gives correct date on second attempt as: 06-28-2020. But in IE it is having issues, from this I understood we can apply one dateformat on the given date, If we want second date format, it should be apply on the fresh date not on the first date format result. And also observe that for first time applying 'MM-DD-YYYY' and next 'MM-DD-YY' is working in IE. For clear understanding please find my question in the link: Date went wrong when using Momentjs date format in IE 11

Prabha
  • 216
  • 3
  • 16
-3

This can help:

export const formatDateToString = date => {
    if (!date) {
        return date;
    }
    try {
        return format(parse(date, 'yyyy-MM-dd', new Date()), 'dd/MM/yyyy');
    } catch (error) {
        return 'invalid date';
    }
};
saran3h
  • 7,930
  • 2
  • 23
  • 33