1

I've not been able to find a solution for a specific date format I want such as Sunday, 31 Oct, 2019. I also require an offset value for the date.

The closest I could get was Sun 31 Oct 2019. I need to be able to offset the date with a number entered by a user. With the script I have below, on certain dates, the day/name returns "undefined" although the other date items return as correct.

Date.prototype.addDays = function(days) {
var date = new Date(this.valueOf());
date.setDate(date.getDate() + days);
return date;}

date = new Date();
offset = effect("Slider Control")("Slider");

dayOffset = offset%7;

myDate = (date.addDays(offset));

dateString = String(myDate);

myMonth = dateString.split(/\s+/).slice(1,3).join(' ');

d = new Date();
days = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
myDay = days[d.getDay()+dayOffset];

myDay + ", " + myMonth

What am I missing? Could you please advise me?

Kate Orlova
  • 3,225
  • 5
  • 11
  • 35
  • Thanks for the reply but I did use this - dayOffset = offset%7 Do take note that "offset" is the user input value to offset from today's date. . – Roland Kahlenberg Sep 03 '19 at 17:38
  • Given you've already added the offset to *myDate*, why not `myDay = days[myDate.getDay()]`. Also, `new Date(this.valueOf())` can be simply `new Date(this)`. – RobG Sep 03 '19 at 20:21

2 Answers2

0

This line:

myDay = days[d.getDay()+dayOffset];

can easily result in accessing beyond the end of the array, in which case you get the value undefined. Consider if it's Friday (day 5) and you add 3 to it. 5 + 3 = 8, but your array's indexes only go up to 6.

To wrap around, use % days.length (or % 7 if you want to hardcode it; I wouldn't):

myDay = days[(d.getDay() + dayOffset) % days.length];

8 % 7 is 1, Monday, which is indeed Friday plus three.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
0

After more research, I found a more robust & elegant code -

enter code hereDate.prototype.addDays = function(days) { enter code herevar date = new Date(this.valueOf()); enter code heredate.setDate(date.getDate() + days); enter code herereturn date;} enter code heredate = new Date(); enter code hereoffset = 5; enter code heremyDate = (date.addDays(offset)); enter code hereoptions = { weekday: 'long', month: 'long', day: 'numeric' }; enter code here(myDate.toLocaleDateString("en-US", options))

I sorta extrapolated info from this answer - How to format a JavaScript date