1
<?php echo date('d M Y'); ?>

Result: 29 Sep 2019

So easy, so elegant!

Seems there is no similar method to do this in javascript?

My try:

let d = new Date();

console.log(d.getDate() + ' ' + (d.getMonth()+1) + ' ' + d.getFullYear()); 

Result: 29 9 2019

But I need short month name instead of integer.

And yes, I saw many solutions using library or creating an array of months names, but I'm interested - is there any native and core javascript way?

FZs
  • 14,438
  • 11
  • 35
  • 45
qadenza
  • 8,611
  • 18
  • 61
  • 108
  • 1
    Possible duplicate of [How to format a JavaScript date](https://stackoverflow.com/questions/3552461/how-to-format-a-javascript-date) – FZs Sep 29 '19 at 18:57

4 Answers4

1

You may be looking for toLocaleDateString

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

let date = new Date()

console.log(date.toLocaleDateString('en-US',options))
Code Maniac
  • 35,187
  • 4
  • 31
  • 54
1

There's no built in way.

You have to manually implement a such feature if you don't want to use a library:

const months=['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec']
const d=new Date()

console.log(`${d.getDate()} ${months[d.getMonth()]} ${d.getFullYear()}`);
//29 Sep 2019

Or, try to use .toLocaleString(), but its return value is implementation-dependent.

FZs
  • 14,438
  • 11
  • 35
  • 45
  • what does it mean - `implementation-dependent` ? – qadenza Sep 29 '19 at 18:45
  • That it isn't written in the ECMAScript standard, and maybe return different value in different browsers/JS-engines – FZs Sep 29 '19 at 18:47
  • @qadenza That it isn't written in the ECMAScript standard, and maybe return different value in different browsers/JS-engines – FZs Sep 29 '19 at 18:48
1

You can use toLocaleDateString()

const date = new Date();
const formattedDate = date.toLocaleDateString('en-GB', {
  day: 'numeric', month: 'short', year: 'numeric'
}).replace(/ /g, '-');
console.log(formattedDate);
novruzrhmv
  • 619
  • 5
  • 12
0

You can use the moment.js library to do this.

https://momentjs.com/docs/#/displaying/

moment().format("D MMM YYYY")
Chris Middleton
  • 5,184
  • 2
  • 29
  • 65