I am trying to take in a date and get the Javascript to verify which quarter that date is in then output the date 1st day of the next quarter.
My code works except for when someone enters the last day of the month on dates that end on the 31st. I figured out this may have something to do with timezones so I get UTC values instead of actual values so I remove the timezone out of the equation.
//get the last completed date entered.
var strDate = $(‘#view_1639-field_812’).val();
let chosenFreq = $(‘#kn-input-field_838 input[type=radio]:checked’ ).closest(‘label’).text().trim()
// verify that we have a frequency
if (chosenFreq !="") {
//verify if strDate is empty
if (strDate != "") {
//Break date down into components
const [month, day, year] =strDate.split("/")
// create a new date object with dates compensate for 0 based month
let fullDate = new Date (Date.UTC(year, parseInt(month)-1,day))
// Get next maintenance date (private funcation see below)
let newDate = GetNewDate(fullDate, chosenFreq)
//output date returned from function
console.log('set new date field' + newDate)
// set date in document
document.getElementById('view_1639-field_847').value = newDate.toLocaleDateString()
/*/
/ Gets a new date based on the frequency and date passed in /
//
function GetNewDate(currDate, frequency) {
//verify you have a frequency string
if (frequency != '') {
//verify we have a date object
if (Object.prototype.toString.call(currDate) === "[object Date]") {
dateDay = new Date(currDate).getUTCDate();
dateMonth = new Date(currDate).getUTCMonth();
dateYear = new Date(currDate).getUTCFullYear();
switch(frequency){
case 'Every 2 years':
currDate.setFullYear(currDate.getFullYear() + 2)
if (currDate.getMonth() > 1) {
currDate.setMonth(1)
}
currDate.setDate(1)
break;
case 'Every 3 weeks':
currDate.setDate(currDate.getDay() + 21)
break;
case 'Every 5 years':
currDate.setFullYear(currDate.getFullYear() + 5)
if (currDate.getMonth() > 1) {
currDate.setMonth(1)
}
currDate.setDate(1)
break;
case 'Yearly':
currDate.setFullYear(currDate.getFullYear() + 1)
if (currDate.getMonth() > 1) {
currDate.setMonth(1)
}
currDate.setDate(1)
break;
case 'Every quarter':
// Get the month of the year as a number (0-11)
const strYear = currDate.getUTCFullYear();
const q1Date = new Date (strYear + '/03/31')
const q2Date = new Date (strYear + '/06/30')
const q3Date = new Date (strYear + '09/30')
// Calculate the quarter of the year
if (currDate <= q1Date) {
console.log('first Quarter')
currDate.setUTCMonth(4)
} else if (currDate <= q2Date) {
console.log('second Quarter')
currDate.setUTCMonth(7)
} else if (currDate <= q3Date) {
console.log('Third Quarter')
currDate.setUTCMonth(10)
} else {
currDate.setMonth(1)
console.log('fourth Quarter')
currDate.setUTCFullYear(currDate.getFullYear() + 1);
}
currDate.setDate(1)
break;
}
}
}
return currDate
}