Reputation: 170
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
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
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,
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(' '));
String#replace
var mydate = new Date('29 Feb 2020');
// replace first nonspace combination along with whitespace
alert(mydate.toDateString().replace(/^\S+\s/,''));
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
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
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