2

I'm using Intl library in my javascript code, as below:

const dateFormat = new Intl.DateTimeFormat(locale, {
    day: '2-digit',
    month: '2-digit',
    year: 'numeric',
});
kk = new Date('1992-10-28')
dateFormat.format(kk, 'en-Us') ==> "10/28/1992"

But I want something like "dd/mm/yyyy" as response:

let format = dateFormat.getFormat('en-Us'); // --> "dd/mm/yyyy"
Priyanka Sharma
  • 167
  • 3
  • 7
  • Possibly a duplicate of [*Where can I find documentation on formatting a date in JavaScript?*](https://stackoverflow.com/questions/1056728/where-can-i-find-documentation-on-formatting-a-date-in-javascript) – RobG Aug 08 '17 at 22:55

1 Answers1

-1

The Intl object doesn't allow you to specify the entire format, only parts of it. If you want a particular sequence of values, you can try a language value that fits or do it by hand. Almost any variant of English other than US will give d, m, y but the separator is another issue. Fortunately, "/" seems to be the default.

Surprisingly, if you provide an English variant that is not recognised, it will likely default to the peculiar US m/d/y sequence.

var d = new Date();
var options = {day:'2-digit', month:'2-digit', year:'numeric'}

console.log(d.toLocaleString('en-gb', options));

Otherwise, a library can help, but if you only want to support one format, a 2 or 3 line function will do.

function formatDMY(date) {
  var z = function(n){return (n<10?'0':'')+n}
  return z(date.getDate()) + '/' +
         z(date.getMonth()+1) + '/' +
         date.getFullYear();
}

console.log(formatDMY(new Date()));
RobG
  • 142,382
  • 31
  • 172
  • 209