-1

I am trying to generate the current date in the Date Month, Year format. Currently I am using following code:

function currentDate() 
{
    var months = [
        'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 
        'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'
    ];

    var date = new Date();
    var d = date.getDate();
    var m = date.getMonth();
    var y = date.getFullYear();

    return `${d} ${months[m]}, ${y}`;
}

Although, It's works perfectly. But, is there a shorter way to do this..?

Something like:

(new Date()).format('d M, Y')
Mr.Singh
  • 1,421
  • 6
  • 21
  • 46
  • 1
    You should check [moment](https://www.npmjs.com/package/moment) library which implement interfaces like you want. – Xeelley Jan 18 '22 at 11:00
  • 1
    Does this answer your question? [How to format a JavaScript date](https://stackoverflow.com/questions/3552461/how-to-format-a-javascript-date) – Ben Fortune Jan 18 '22 at 11:03
  • @Xeelley Moment library got deprecated. – Sivakumar A Jan 18 '22 at 11:03
  • @Xeelley [luxon](https://moment.github.io/luxon) is moment's successor – shaedrich Jan 18 '22 at 11:06
  • Actually, I am trying to refactor and reduce the code. Therefore, I am not in favor of including any external library. I thought this can be reduced as well, so I posted the question. – Mr.Singh Jan 18 '22 at 11:19
  • @BenFortune, I have already seen that question and it did not help as I have mentioned in my last comment. – Mr.Singh Jan 18 '22 at 11:21
  • As suggested in my answer and in the linked question, you can use [`Intl.DateTimeFormat`](https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat) instead – shaedrich Jan 18 '22 at 11:22

2 Answers2

2

Unfortunately, there isnt.

But you can use libraries like luxon:

DateTime.now().toFormat('d M, Y')

Or, if you want to stay native, you can use Intl.DateTimeFormat:

new Intl.DateTimeFormat('es-US', { dateStyle: 'full' }).format(d);

However, ECMAScript currently has a proposal to improve Date class by adding Temporal global object:

Temporal.now.date().toLocaleString('es-US', {
  weekday: 'long',
});
shaedrich
  • 5,457
  • 3
  • 26
  • 42
0

There is no simple way to do that. Instead, you could see other alternatives.

If you are already using new Date() all over the application. I suggest dayjs. It has all the date-utilities you are looking for.

It works with new Date() object also.

Sivakumar A
  • 601
  • 1
  • 6
  • 16