Magthuzad
Magthuzad

Reputation: 170

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 be able to handle the date in the format that is written below as code.

var mydate = new Date('29 Feb 2020');
alert(mydate.toDateString());

Thank you for reading this question and hope i make clear what my problem is

Upvotes: 10

Views: 20084

Answers (4)

MSM
MSM

Reputation: 444

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

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

alert(formattedDate)

Upvotes: 4

Pranav C Balan
Pranav C Balan

Reputation: 115232

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 = new Date('29 Feb 2020');
// split  based on whitespace, then get except the first element
// and then join again
alert(mydate.toDateString().split(' ').slice(1).join(' '));


2. Using String#replace

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


3. Using String#indexOf and String#substr
var mydate = new Date('29 Feb 2020');
// get index of first whitespace
var str = mydate.toDateString();
// get substring
alert(str.substr(str.indexOf(' ') + 1));

Upvotes: 32

Tomas Varga
Tomas Varga

Reputation: 1440

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.

Upvotes: 3

Senad Meškin
Senad Meškin

Reputation: 13756

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.

Upvotes: 0

Related Questions