0

I need to get "Jun" for "June" and "Mon" for "Monday". The problem is looking up in an object of english words doesn't work if user has their language set to anything other than English.

export const shortDate = (str: any) => {
    const d = new Date(str);
    const dateString =
        daysOfWeek[d.getDay()].toUpperCase() +
        ', ' +
        shortMonths[d.getMonth()] +
        ' ' +
        d.getDate() +
        nth(d.getDate());

    return dateString;
};

I need to get rid of the shortMonths object and the dayOfWeek since this will be different when user is not English speaker.

chovy
  • 72,281
  • 52
  • 227
  • 295
  • 1
    This is what [Intl.DateTimeFormat](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/DateTimeFormat) is for. – Tom Mar 14 '22 at 20:53
  • 1
    See [`Date.prototype.toLocaleString`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleString). Use `d.toLocaleString("en-US", { weekday: "short" })` and `d.toLocaleString("en-US", { month: "short" })`. – Sebastian Simon Mar 14 '22 at 20:55

1 Answers1

3

Check out Intl.DateTimeFormat:

var date = new Date();

var options = { weekday: 'short', month: 'short' };
console.log(new Intl.DateTimeFormat('en-US', options).format(date));

Or as Sebastian points out above, date.toLocaleString:

const date = new Date()

console.log(date.toLocaleString('en-US', { weekday: 'short' }))
console.log(date.toLocaleString('en-US', { month: 'short' }))
ray
  • 26,557
  • 5
  • 28
  • 27