0

I found the following code on this site and it works great for what I am trying to do. The only thing I can't figure out is how to format the dates that are outputting.

The variable that I am specifically looking at formatting is the nextq variable. Currently it outputs like Tue Oct 01 2019 00:00:00 GMT-0400 (Eastern Daylight Time).

I am wanting to simplify this to where it would say "Tuesday (Tues is fine), Oct 01, 2019 - with no time. Alternatively, Tues, 10/01/19. Either one would work.

How would I do this when the date is already formatted?

var today = new Date();
var quarter = Math.floor((today.getMonth() + 3) / 3);
var nextq;
if (quarter == 4) {
    nextq = new Date (today.getFullYear() + 1, 1, 1);
} else {
    nextq = new Date (today.getFullYear(), quarter * 3, 1);
}
var millis1 = today.getTime();
var millis2 = nextq.getTime();
var daydiff = (millis2 - millis1) / 1000 / 60 / 60 / 24;
console.log("Check2 " + daydiff);
daydiffRound = Math.floor(daydiff);
console.log("check2 round " + daydiffRound);
console.log("Check2 date " + nextq);
Paul
  • 3,348
  • 5
  • 32
  • 76

1 Answers1

1

The Date object isn't "already formatted" - when you pass it in this way its toString() method is invoked and returned as an ECMA-262-compliant string representation based on the information associated with tha instance of Date.

You can cobble your format together using a combination of the Date object's toLocaleString(), getDate() and getFullYear() methods, like so:

var today = new Date();
var quarter = Math.floor((today.getMonth() + 3) / 3);
var nextq;
if (quarter == 4) {
    nextq = new Date (today.getFullYear() + 1, 1, 1);
} else {
    nextq = new Date (today.getFullYear(), quarter * 3, 1);
}

console.log("nextq: " + nextq.toLocaleString('en-us', {  weekday: 'long' }) + ", " + nextq.toLocaleString('default', { month: 'long' }) + " " + ("0" + nextq.getDate()).slice(-2) + ", " + nextq.getFullYear());
esqew
  • 42,425
  • 27
  • 92
  • 132
  • Thanks. What does the `weekday: 'long'` and `month: 'long'` code do in your solution? – Paul Jul 31 '19 at 17:16
  • @Paul if you refer to the linked documentation page for [`toLocaleString()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleString), specifically within [the Parameters section](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleString#Parameters), you'll see the `long` value for the `weekday` option key adjusts the result to output the full spelling of the day of the week. Similarly, the `long` value for the `month` option key adjusts the result to output the full spelling of the month. – esqew Jul 31 '19 at 17:20
  • 1
    Thanks for the clarification. I missed that while viewing. I appreciate your help! – Paul Jul 31 '19 at 17:21