问题
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
回答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 = 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));
回答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.
回答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.
来源:https://stackoverflow.com/questions/48384163/javascript-remove-day-name-from-date