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?
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?
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.
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}`)
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));