Skip to content Skip to sidebar Skip to footer

Javascript Remove Day Name From Date

i wanted to ask if someone knows how to remove the Day Name from the following example,the alert returns Sat Feb 29 2020, im not using Moment.js only Jquery because i only need to

Solution 1:

The Date#toDateString method would result always returns in that particular format.

So either you need to generate using other methods available or you can remove using several ways,


1. Using String#split, Array#slice and Array#join

var mydate = newDate('29 Feb 2020');
// split  based on whitespace, then get except the first element// and then join againalert(mydate.toDateString().split(' ').slice(1).join(' '));


2. Using String#replace

var mydate = newDate('29 Feb 2020');
// replace first nonspace combination along with whitespacealert(mydate.toDateString().replace(/^\S+\s/,''));


3. Using String#indexOf and String#substr
var mydate = newDate('29 Feb 2020');
// get index of first whitespacevar str = mydate.toDateString();
// get substringalert(str.substr(str.indexOf(' ') + 1));

Solution 2:

If you've got a Date object instance and only want some parts of it I'd go with the Date object API:

mydate.getDate() + ' ' + mydate.toLocaleString('en-us', { month: "short" }) + ' ' + mydate.getFullYear()

Just keep in mind the functions are local time based (there are UTC variants, e.g. getUTCDate()), also to prevent some confusion getMonth() is zero-based. Working with dates in JavaScript is where the real fun begins ;)

The toLocaleString function is relatively new though (IE11+), check other possibilities if you need to support older browsers.

Solution 3:

Easiest way is to replace all alpha characters from a string. That way you will not make mistake once day name is in a different position.

var withoutDay = '29 Feb 2020'.replace(/[a-zA-Z]{0,1}/g,'').replace('  ', ' ');
alert(withoutDay);

Code replace(/[a-zA-Z]{0,1}/g,'') will replace all alpha characters from string and replace(' ', ' '); will remove double spaces.

I hope this helps.

Solution 4:

Proper way is to use DateTimeFormat. You can play around by manipulating the format object inside DateTimeFormat.

let myDate = newDate('29 Feb 2020');
let formattedDate = newIntl.DateTimeFormat("en-US", {
  year: "numeric",
  month: "short",
  day: "2-digit",
}).format(myDate);

alert(formattedDate)

Post a Comment for "Javascript Remove Day Name From Date"