2

When using javascript's built in Intl.DateTimeFormat to format the date, if you provide the format {weekday : 'short', day 'numeric'} it will re-arrange the two and always give day followed by weekday.

For reference:

console.log(new Intl.DateTimeFormat('en-US', {
  weekday: 'short',
  day: 'numeric'
}).format(new Date));

I would expect Fri 3 but instead I receive 3 Fri

Am I using this incorrectly or is this a bug?

The immediate workaround I've tried is to format for just weekday, then just day, then append the two which works but this isn't ideal for my project.

Barmar
  • 741,623
  • 53
  • 500
  • 612
Levon
  • 171
  • 1
  • 7
  • `Intl.DateTimeFormat` doesn't provide a way for you to specify the order of each part of the date, it uses the expected order for the locale. There's no standard order for just weekday and day, though. It's not a common way that dates are printed. – Barmar May 03 '19 at 22:20
  • The order of properties in an object is not considered significant. All that matters is whether the properties exist. – Barmar May 03 '19 at 22:20
  • no feedback ? !! – Mister Jojo May 05 '19 at 00:44

3 Answers3

0

en-US is allways day / weekday, => use en-GB

let
  date3may = new Date('May 3, 2019 15:24:00'),
  Options  = {weekday:'short', day:'numeric'};

console.log(new Intl.DateTimeFormat('en-GB', Options).format(date3may));
Mister Jojo
  • 20,093
  • 6
  • 21
  • 40
0

The order of the output is defined by the locale.

If you want to avoid concatenation, you can use a different English locale, for example en-AU:

    var date = new Date();

    console.log(new Intl.DateTimeFormat('en-AU', {
      weekday: 'short',
      day: 'numeric'
    }).format(date));

For a list of all possible locales, you can refer here (MDN) or here (StackOverflow).

ludovico
  • 2,103
  • 1
  • 13
  • 32
0

According to MDN, the correct way to achieve what you want, with consistent results, is to use Intl.DateTimeFormat.prototype.formatToParts() method and then manually manipulate the given array.

My first approach would be as follows:

let date = new Date();
let order = ['weekday', 'day'];

new Intl.DateTimeFormat('en-US', {
    weekday: 'short',
    day: 'numeric'
}).formatToParts(date).filter((elem) => {
    return (elem.type !== 'literal');
}).sort((a, b) => {
    // SET ORDER
    let i = 0;
    a.index = -1;
    b.index = -1;
    order.forEach((type) => {
       if (a.type === type) {
           a.index = i;
       }
       if (b.type === type) {
           b.index = i;
       }
       i++;
    });
    return (a.index - b.index);
}).map(({type, value}) => {
    // MODIFY ELEMENT
    switch (type) {
        default : return (value);
    }
}).reduce((string, part) => string + ' ' + part);
Ernesto Stifano
  • 3,027
  • 1
  • 10
  • 20