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
  • 16,581
  • 13
  • 41
  • 50
qadenza
  • 9,025
  • 18
  • 73
  • 126
  • 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
  • 37,143
  • 5
  • 39
  • 60
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
  • 16,581
  • 13
  • 41
  • 50
  • 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
  • 639
  • 5
  • 13
0

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

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

moment().format("D MMM YYYY")
Chris Middleton
  • 5,654
  • 5
  • 31
  • 68