0

I have this date string, and I need to get back only the date (month and day and year):

  var date1 = new Date('August 19, 1975 23:15:30 GMT+11:00');

I need to get back only this string:

  var dateOnly = 'August 19, 1975' 

How do I do it?

Yanshof
  • 9,659
  • 21
  • 95
  • 195
  • https://stackoverflow.com/questions/3552461/how-to-format-a-javascript-date – mahval Oct 18 '18 at 10:25
  • 1
    Possible duplicate of [How to format a JavaScript date](https://stackoverflow.com/questions/3552461/how-to-format-a-javascript-date) – Tiago Mussi Oct 18 '18 at 10:27

3 Answers3

1

Don't bother with the dates by yourself and don't create helper functions. Use an established date formatter/converter like moment.js:

const date1 = moment('August 19, 1975 23:15:30 GMT+11:00');
console.log(date1.format('MMM DD, YYYY'));

Of course, in your case you could just split the string by spaces and take the first half:

const date1 = 'August 19, 1975 23:15:30 GMT+11:00';
console.log(date1.split(' ', 2).join(' '))

The trick is the number 2 here which means cutting until the second space in the string.

0

Use .toString() and object destructuring to get desired result as below -

var date1 = new Date('August 19, 1975 23:15:30 GMT+11:00');

var [day, month, date, year] = date1.toString().split(' ')

console.log(`${month} ${date}, ${year}`)
Nitish Narang
  • 4,124
  • 2
  • 15
  • 22
  • This won't always work. In the date string, there is also time zone passing. GMT+11:00. So it can change the date to 20 or 18. you will get a different result based on current time. – parth Oct 18 '18 at 10:29
0

You can use toLocaleDateString with options.

var date = new Date('August 19, 1975 23:15:30 GMT+11:00');
var options = { year: 'numeric', month: 'long', day: 'numeric' };
console.log(date.toLocaleDateString("en-US", options));
barbsan
  • 3,418
  • 11
  • 21
  • 28