0

I am trying to display a long date format (Apr 04 2018) using a string method. They only method I have learned is .toDateString, which includes the weekday, how do I display it without the weekday? I got it to display using and array and .get method, but my instructor specifically stated we must use a string method. I have searched several educational sites, w3shcools, sitepoint, etc. Can anyone point me in the right direction?

Racil Hilan
  • 24,690
  • 13
  • 50
  • 55
  • Could you show us the code you are using now? – Merijndk Apr 06 '18 at 15:03
  • 1
    I don't think any of [the other built-in string methods](https://stackoverflow.com/a/10685571/243245) match. It might be easiest to take that string and remove the day part, e.g. with a regex. – Rup Apr 06 '18 at 15:06
  • While I have used regex in one of my programming classes, it is not something that we have covered in Web Programming, will have to see if he will allow us to use it. Thanks! – Christy Bartholomew Apr 06 '18 at 15:44

3 Answers3

1

You could do it like this:

date.toDateString().replace(/^\w+ /, '');

For more sophisticated control over date formatting, I'd use a separate package like Moment.js: https://momentjs.com/

kshetline
  • 12,547
  • 4
  • 37
  • 73
1

You can use substring(4) to remove the first 3 characters for the day abbreviation and the following space:

console.log(new Date().toDateString().substring(4));
Racil Hilan
  • 24,690
  • 13
  • 50
  • 55
-2

You could do something like this http://jsfiddle.net/EZVbj/1589/

HTML:

<div id="para1"></div>

Javascript:

document.getElementById("para1").innerHTML = formatAMPM();

function formatAMPM() {
var d = new Date(),
    months = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'],
    days = ['Sun','Mon','Tue','Wed','Thu','Fri','Sat'];
return days[d.getDay()]+' '+months[d.getMonth()]+' '+d.getDate()+' '+d.getFullYear();
}

Ouput: Fri Apr 6 2018

John S
  • 21
  • 4
  • 1
    Your output: `Fri Apr 6 2018` - Requested output: `Apr 06 2018` – Nope Apr 06 '18 at 15:13
  • You can easily fix that by removing the days[d.getDay()]+' '+ in the return – John S Apr 06 '18 at 15:18
  • 2
    That was the whole point of OPs question. You re-created the problem OP has without adding a solution. That is not an answer that is reiterating the problem in an alternative way! The Result should not contain the day and it should have a 2-digit day value `06` and not `6` – Nope Apr 06 '18 at 15:19
  • Wow, that is a lot of feedback in a short period of time. Thank you so much everyone! – Christy Bartholomew Apr 06 '18 at 15:36