I am encountering an issue with JavaScript when trying to obtain the first day of the week. It seems to be functioning correctly for most cases, but there is a discrepancy when it comes to the first day of the month.
Could there be something that I am overlooking here?
Let's review the following two scenarios:
1) Example: 05/02/2014
<script>
var d = new Date(Date.UTC(2014, 4, 2, 0, 0, 0));
var day = d.getUTCDay();
var indate = d.getUTCDate();
var diff = indate - day + (day == 0 ? -7 : 0); // adjusting for Sunday as first day of the week
var sunday = new Date(d.setDate(diff));
document.write('\nday:' + day);
document.write('\nindate:' + indate);
document.write('\nsunday:' + sunday);
document.write('\diff:' + diff);
</script>
Result: day: 5 indate: 2 sunday: Sun Apr 27 2014 17:00:00 GMT-0700 (Pacific Daylight Time) diff: -3
2) Example: 05/01/2014
<script>
var d = new Date(Date.UTC(2014, 4, 1, 0, 0, 0));
var day = d.getUTCDay();
var indate = d.getUTCDate();
var diff = indate - day + (day == 0 ? -7 : 0); // adjusting for Sunday as first day of the week
var sunday = new Date(d.setDate(diff));
document.write('\nday:' + day);
document.write('\nindate:' + indate);
document.write('\nsunday:' + sunday);
document.write('\diff:' + diff);
</script>
Result: day: 4 indate: 1 sunday: Fri Mar 28 2014 17:00:00 GMT-0700 (Pacific Daylight Time) diff: -3
Thank you in advance for any assistance provided!