简体   繁体   中英

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

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));

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, eg 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.

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.

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM