Get dates for last quarter and this quarter through Javascript - javascript

I'm trying to create a report that needs to get the dates for last quarter and this quarter through Javascript. The code worked last month but in March it doesn't work. It shows last quarter as this quarter and this quarter shows as next quarter. I am using datejs in this project. Here is the code I am using:
function thisQuarterDates(from, to) {
var month = Date.parse('today').toString('MM');
var quarterMonth = (Math.floor(month/3)*3)+1;
var year = Date.parse('today').toString('yyyy');
var quarterStartDate = (quarterMonth < 10) ? quarterMonth+'/1/' +year : quarterMonth+'/1/'+ year;
var quarterEndDate = Date.parse(quarterStartDate).add(2).months().moveToLastDayOfMonth().toString('M/d/yyyy');
var today = Date.parse('today').toString('M/d/yyyy');
document.getElementById(from).value = quarterStartDate;
document.getElementById(to).value = quarterEndDate;
}
function lastQuarterDates(from, to) {
var month = Date.parse('today').toString('MM');
var quarter = (Math.floor(month/3))+1;
var lastQuarter = (quarter > 1) ? quarter - 1 : lastQuarter = 4;
var year;
if (((((lastQuarter-1)*3)+1) < 10))
{
year = Date.parse('today').toString('yyyy');
}
else
{
year = Date.parse('today').add(-1).years().toString('yyyy');
}
var firstDate = ((((lastQuarter-1)*3)+1) < 10) ? (((lastQuarter-1)*3)+1) +'/1/'+ year : (((lastQuarter-1)*3)+1) +'/1/'+ year;
var lastDate = Date.parse(firstDate).add(2).months().moveToLastDayOfMonth().toString('M/d/yyyy');
document.getElementById(from).value = firstDate;
document.getElementById(to).value = lastDate;
}
Anyone know why it's incorrect or is there an easier way?

Simple generic solution in pure JS. First calculate quarter number:
const today = new Date();
const quarter = Math.floor((today.getMonth() / 3));
Next, current quarter:
const startFullQuarter = new Date(today.getFullYear(), quarter * 3, 1);
const endFullQuarter = new Date(startFullQuarter.getFullYear(), startFullQuarter.getMonth() + 3, 0);
Previous quarter
const startFullQuarter = new Date(today.getFullYear(), quarter * 3 - 3, 1);
const endFullQuarter = new Date(startFullQuarter.getFullYear(), startFullQuarter.getMonth() + 3, 0);
Add or subtract 3's per quarter in expression new Date(today.getFullYear(), quarter * 3 - x, 1) to get future or past quarters.

if you're using moment.js this might be easier:
var quarterAdjustment= (moment().month() % 3) + 1;
var lastQuarterEndDate = moment().subtract({ months: quarterAdjustment }).endOf('month');
var lastQuarterStartDate = lastQuarterEndDate.clone().subtract({ months: 3 }).startOf('month');
conversion to date.js should be fairly easy.

Using moment.js library its very simple to get the start and end date of a particular quarter as follows:
Start date of last quarter = moment().subtract(lastQuarterNumber, 'quarter').startOf('quarter');
End date of last quarter = moment().subtract(lastQuarterNumber, 'quarter').endOf('quarter');
Start date of current quarter = moment().startOf('quarter');
End date of current quarter = moment().endOf('quarter');

On the first function change
var quarterMonth = (Math.floor(month/3)*3)+1;
with
var quarterMonth = (Math.floor((month-1)/3)*3)+1;
and on the second function
var quarter = (Math.floor(month/3))+1;
with
var quarter = (Math.floor((month-1)/3))+1;
and I think it will be fine.
And on the second function I don't see the point of
((((lastQuarter-1)*3)+1) < 10)
a simple
(lastQuarter < 4)
will do the same job

Using moment.js:
This quarter START: moment().startOf('quarter')
This quarter END: moment().endOf('quarter')
Previous quarter START: moment().subtract(1, 'quarter').startOf('quarter')
Previous quarter END: moment().subtract(1, 'quarter').endOf('quarter')
Next quarter START: moment().add(1, 'quarter').startOf('quarter')
Next quarter End: moment().add(1, 'quarter').endOf('quarter')

I have been using date-fns library for some time now. The methods it exposes can be immensely useful in solving such problems.
You can make use of addQuarter and subQuarter methods.
Code would look something like:
const lastQuarterStartDate = startOfQuarter(subQuarters(new Date(2014, 8, 1),1))
const lastQuarterEndDate = lastDayOfQuarter(subQuarters(new Date(2014, 8, 1),1))
const thisQuarterStartDate = startOfQuarter(new Date(2014, 8, 1))
const thisQuarterEndDate = lastDayOfQuarter(new Date(2014, 8, 1))
Reference: https://date-fns.org/v2.21.2/docs/addQuarters

Use this simple code to get all quarter based on january and april
Demo
Code :
// startMonth should be january or april
function setQuarter(startMonth) {
var obj = {};
if(startMonth=='january'){
obj.quarter1 = {start:moment().month(0).startOf('month'),end:moment().month(2).endOf('month')}
obj.quarter2 = {start:moment().month(3).startOf('month'),end:moment().month(5).endOf('month')}
obj.quarter3 = {start:moment().month(6).startOf('month'),end:moment().month(8).endOf('month')}
obj.quarter4 = {start:moment().month(9).startOf('month'),end:moment().month(11).endOf('month')}
console.log(obj);
return obj;
}
else if(startMonth=='april'){
obj.quarter1 = {start:moment().month(3).startOf('month'),end:moment().month(5).endOf('month')}
obj.quarter2 = {start:moment().month(6).startOf('month'),end:moment().month(8).endOf('month')}
obj.quarter3 = {start:moment().month(9).startOf('month'),end:moment().month(11).endOf('month')}
obj.quarter4 = {start:moment().month(0).startOf('month').add('years',1),end:moment().month(2).endOf('month').add('years',1)}
console.log(obj);
return obj;
}
}
setQuarter('april');
Fiddle

Using this we can get Quarter's start and end dates dynamically irrespective of start of the financial year(Quarter).
var fYearStart=new Date('2021-1-29') //Pass your financial year's start date
var q1Start=new Date(fYearStart.getFullYear(),fYearStart.getMonth(),1)
var dummy1=new Date(fYearStart.getFullYear(),fYearStart.getMonth(),1)
var dummy5=new Date(fYearStart.getFullYear(),fYearStart.getMonth(),1)
var q1End=new Date(dummy1.setMonth(dummy1.getMonth()+3))
var q1FinalEnd=new Date(dummy5.setMonth(dummy5.getMonth()+3))
q1FinalEnd.setSeconds(q1End.getSeconds()-1)
console.log(q1Start.toLocaleString())
console.log(q1FinalEnd.toLocaleString())
var q2Start=new Date(q1End.getFullYear(),q1End.getMonth(),1)
var dummy2=new Date(q1End.getFullYear(),q1End.getMonth(),1)
var dummy6=new Date(q1End.getFullYear(),q1End.getMonth(),1)
var q2End=new Date(dummy2.setMonth(dummy2.getMonth()+3))
var q2FinalEnd=new Date(dummy6.setMonth(dummy6.getMonth()+3))
q2FinalEnd.setSeconds(q2End.getSeconds()-1)
console.log(q2Start.toLocaleString())
console.log(q2FinalEnd.toLocaleString())
var q3Start=new Date(q2End.getFullYear(),q2End.getMonth(),1)
var dummy3=new Date(q2End.getFullYear(),q2End.getMonth(),1)
var dummy7=new Date(q2End.getFullYear(),q2End.getMonth(),1)
var q3End=new Date(dummy3.setMonth(dummy3.getMonth()+3))
var q3FinalEnd=new Date(dummy7.setMonth(dummy7.getMonth()+3))
q3FinalEnd.setSeconds(q3End.getSeconds()-1)
console.log(q3Start.toLocaleString())
console.log(q3FinalEnd.toLocaleString())
var q4Start=new Date(q3End.getFullYear(),q3End.getMonth(),1)
var dummy4=new Date(q3End.getFullYear(),q3End.getMonth(),1)
var dummy8=new Date(q3End.getFullYear(),q3End.getMonth(),1)
var q4End=new Date(dummy4.setMonth(dummy4.getMonth()+3))
var q4FinalEnd=new Date(dummy8.setMonth(dummy8.getMonth()+3))
q4FinalEnd.setSeconds(q4End.getSeconds()-1)
console.log(q4Start.toLocaleString())
console.log(q4FinalEnd.toLocaleString())

Related

days left until user's bday

I've created a pirate speak program.
It asks the user for their name and date of birth and calculates the years from the input and added 100 years for fun. I also need to calculate the number of days left until their birthday using user input but I don't know what to do. I've tried some methods and stuff but its not working. any tips or mistakes I need to fix?
var name = prompt('What\'s yer name?');
var date = prompt('What\'s yer date o\' birth? (mm/dd/yyyy)');
let years = date;
let num = years.substring(6, 10);
var myInput = parseInt(num);
var x = myInput;
var y = 100;
var result = x + y;
console.log(`Ahoy, ${name}. It will be th\' year ${result} when ye be 100 years barnacle-covered.`);
var myInput = parseInt(date);
var bday = myInput;
function daysUntilNext(month, day){
var tday= new Date(), y= tday.getFullYear(), next= new Date(y, month-1, day);
tday.setHours(0, 0, 0, 0);
if(tday>next) next.setFullYear(y+1);
return Math.round((next-tday)/8.64e7);
}
var d= daysUntilNext(date);
console.log(d+' day'+(d>1? 's': '')+' until yer birthday');
Ok, I have cleaned up your JavaScript a little. Best practice was to get the date from the string and parse each part then just create a Date object from there. What's easier in the future is to use a datepicker HTML component rather than a string, but I understand that wasn't your goal for this.
Next, do the plus 100 calculation and display that result.
Lastly, take the Date object we made and take the information that we need from it. FWIW getDay() returns the day of the week, you want getDate() which return the day of the month. Then calculate how many days away from those in the next year. Display that result in the console.
I think you were getting that NAN because you were doing calculations on strings not numbers or it was because there weren't enough parameters in daysUntilNext(), so you were operating on null or undefined somewhere
var name = prompt('What\'s yer name?');
var birthDateString = prompt('What\'s yer date o\' birth? (mm/dd/yyyy)');
var daySubstring = birthDateString.substring(3, 5);
var monthSubstring = birthDateString.substring(0, 2);
var yearSubstring = birthDateString.substring(6, 10);
var birthdate = new Date(parseInt(yearSubstring), parseInt(monthSubstring) - 1, parseInt(daySubstring));
var ONE_HUNDRED = 100;
var result = parseInt(yearSubstring) + ONE_HUNDRED;
console.log(`Ahoy, ${name}. It will be th\' year ${result} when ye be 100 years barnacle-covered.`);
function daysUntilNext(month, day) {
var today = new Date();
var year = today.getFullYear();
var next = new Date(year, month, day);
today.setHours(0, 0, 0, 0);
if (today > next) next.setFullYear(year + 1);
return Math.round((next - today) / 8.64e7);
}
var d = daysUntilNext(birthdate.getMonth(), birthdate.getDate());
console.log(d + ' day' + (d > 1 ? 's' : '') + ' until yer birthday');
The other answerer's code is correct, but not clear. Here's the same, only more user-friendly.
The difference is that single-digit months or days won't bother you.
I hope I could help.
var name = prompt('What\'s yer name?');
var birthDateString = prompt('What\'s yer date o\' birth? (mm/dd/yyyy)');
var inputdate = birthDateString.split("/");
var daySubstring = inputdate[1];
var monthSubstring = inputdate[0];
var yearSubstring = inputdate[2];
var birthdate = new Date(parseInt(yearSubstring), parseInt(monthSubstring) - 1, parseInt(daySubstring));
var ONE_HUNDRED = 100;
var result = parseInt(yearSubstring) + ONE_HUNDRED;
console.log(`Ahoy, ${name}. It will be th\' year ${result} when ye be 100 years barnacle-covered.`);
function daysUntilNext(month, day) {
var today = new Date();
var year = today.getFullYear();
var next = new Date(year, month, day);
today.setHours(0, 0, 0, 0);
if (today > next) next.setFullYear(year + 1);
return Math.round((next - today) / 8.64e7);
}
var d = daysUntilNext(birthdate.getMonth(), birthdate.getDate());
console.log(d + ' day' + (d > 1 ? 's' : '') + ' until yer birthday');

Creating an array of dates between 2 dates

I have 2 dates: startdate and enddate. End date is always a day less than the startdate. So if my start day is 19th, the end date would be on the 18th of next month.
I am trying to create an array of number of days in between the 2 dates.
(It goes from 19th to 18th and then 18th to 18th of every month to calculate the difference)
Example
8/19/2018 - 9/18/2018 = 30 days
9/18/2018 - 10/18/2019 = 30 days
10/18/2018 - 11/18/2018 = 31 days
array = [30,30,31]
I am using the following code to calculate days difference between the dates.
function daysBetweenArrears (date1, date2){
date1.setDate(date1.getDate() );
date2.setDate(date2.getDate() - 1);
var Diff = Math.abs(date2.getTime() - date1.getTime());
var TimeDifference = Math.round(Diff / (1000 * 3600 * 24));
return TimeDifference;
}
The following code for creating the array
if (document.getElementById("endDate"))
y = document.getElementById("endDate").value;
if (document.getElementById("startDate"))
z = document.getElementById("startDate").value;
var dateArr = getDateArray(z, y);
var dayCountArr = "";
var b = [];
for (var x = 0; x < dateArr.length-1; x++)
{
dayCountArr += daysBetweenArrears(dateArr[x], dateArr[x+1], ",");
b.push(daysBetweenArrears(dateArr[x], dateArr[x+1]));
}
The issue is that when i set the date as following, it is giving me incorrect output. The problem is that it is setting the dates incorrectly whenever it goes to the next month. I am not sure what i am doing wrong here. Any help is greatly appreciated. Thank you.
date2.setDate(date2.getDate() - 1);
You can do this using moment. Hope this helps.
const start = "8/19/2018";
const end = "11/18/2018 ";
const dates = [];
const mstart = moment(new Date(start));
const mend = moment(new Date(end));
for (let i = 0; mstart < mend ; i++) {
const daysInMonth = mstart.daysInMonth() + (i === 0 ? -1 : 0);
dates.push(daysInMonth);
mstart.add(1, 'M');
}
console.log(dates);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"></script>
You can update your function daysBetweenArrears
const daysBetweenArrears = (date1, date2) => {
const time1 = new Date(date1).getTime();
const time2 = new Date(date2).getTime();
const diff = Math.abs(time2 - time1);
return Math.round(diff/(1000*60*60*24));
};
console.log(daysBetweenArrears('8/18/2018', '9/18/2018'));
console.log(daysBetweenArrears('6/18/2018', '7/18/2018'));

How to check if the date having more than one year from current year

I am trying to check if the date i.e. (07/02/2018 ) is more than year from current date and if the date i.e. (07/02/2018 ) is less than year from current date using JavaScript tried with following code
var x = new Date('JUN-2016');
var y = new Date('MAY-2016');
console.log(+x < +y);
Your question is not very clear to me but this may help you:
var now = new Date();
var then = new Date('07/02/2018');
var diffInDays = Math.round((then-now) / (1000*60*60*24));
console.log('then is', diffInDays, 'days more than now.');
Note: If diffInDays is a positive number then the then is more than now, otherwise it's less.
You can simply add 1000*60*60*24*365 milliseconds to your first date and compare it to your second date :
var x = new Date('APR-2015');
var y = new Date('MAY-2016');
console.log(+x + 1000*60*60*24*365 < +y);
var x2 = new Date('SEP-2015');
console.log(+x2 + 1000*60*60*24*365 < +y);
You can get the year with the getFullYear()method (Date doc).
let x = new Date();
let y = new Date();
x_year = x.getFullYear();
y_year = y.getFullYear();
// The you just have to compare the year
One way to do it, although I'd be surprised if there wasn't a better way:
var x = new Date();
x = x.setFullYear(x.getFullYear() + 1);
x = new Date(x);
var y = (new Date('2018-04-08'));
var z = (new Date('2019-04-08'));
if (y < x) {
console.log('Y is less than a year from now');
} else {
console.log('Y is more or exactly a year from now');
}
if (z < x) {
console.log('Z is less than a year from now');
} else {
console.log('Z is more or exactly a year from now');
}
Your question is not clear this is based on my assumption.
I am assuming that you need to check if the given date is one year ahead of the current date.
var x = new Date('1, 1, 2018');
var today = new Date();
var time = Math.abs(today.getTime() - x.getTime());
var days = Math.ceil(time / (1000 * 3600 * 24));
alert("There is a difference of " + days + " days between today and the given date");
I am assuming that you want to know if some arbitrary date is less or more than a year from current date.
We can get a the value for a year this way:
var a_year = Math.abs(new Date('01-01-2018'.replace(/-/g,'/')) - new Date('01-01-2017'.replace(/-/g,'/')));
Then we set two date tests:
var test1 = '01-01-2018';
var test2 = '01-01-2015';
Calculate the diffs:
var diff1 = Math.abs(new Date() - new Date(test1.replace(/-/g,'/')));
var diff2 = Math.abs(new Date() - new Date(test2.replace(/-/g,'/')));
Then you can log the results for testing:
console.log(diff1 > a_year)
console.log(diff1 < a_year)
console.log(diff2 > a_year)
console.log(diff2 < a_year)
Credits to David Hedlund's answer on How to subtract date/time in javascript?

how to compare a user entered date to the current date and change a fields background color?

I am new to javascript and am working on a fallible PDF form and trying to set it to do multiple things. The first is I need to compare a user entered date to the current date to see if it is withing 5 years to the day. The second thing I need it to do is to change a fields background color if that date is at the 5 year time or outside of that range. This is the code I have been trying but it hasn't worked so far. There are 37 fields that need to be checked by this.
for(i=1;i<38;i++){
var Y = d.getFullYear();
var d = new Date();
var M = d.getMonth();
var d = new Date();
var D = d.getDay(); //n =2
var strDate = this.getField("Text"+[i]).value;
var arrDate = strDate.split('/');
var month = arrDate[0];
var day = arrDate[1];
var year = arrDate[2];
if(year+5>=Y){
if(M<=month){
if(D<=day){
this.getField("Text[i]").fillColor=color.red;
}}}}
I have updated this, it working now, can you try this now ?
for(i=1;i<38;i++)
{
var todayDate = new Date();
var strDate = "12/25/2009";
var arrDate = strDate.split('/');
var month = arrDate[0];
var day = arrDate[1];
var year = parseInt(arrDate[2]) + 5;
var userEnteredDate = new Date(year, month, day);
if(userEnteredDate <= todayDate)
{
//Color change code here...
}
}
The simplest approach so far as I know, is to instantiate a Date that is five years ago based on current time:
var t = new Date()
t.setFullYear(t.getFullYear() - 5) // t is five years ago
Then you just need to substract the user input date with this one, and see if the result is positive or negative:
var ut = new Date("......") // the Date instance from user input
if(ut - t >= 0) {
// within 5 years
} else {
// more than 5 years ago
}
The reason you can do so, is because when you substract two Date instances one another, they will be internally converted to timestamps. The less a timestamp is, the earlier the time is. So the result of substraction (a number) represents the time in between, in milliseconds.
If you don't care how long in between, you could just compare them:
var ut = new Date("......") // the Date instance from user input
if(ut >= t) {
// within 5 years
} else {
// more than 5 years ago
}
Try this
var d = new Date(),
Y = d.getFullYear(),
M = d.getMonth() + 1, // since this returns 0 - 11
D = d.getDay() + 1, // since this returns 0 - 30
strDate,
arrDate,
month,
day,
year;
for(var i = 1; i < 38; i++) {
strDate = this.getField("Text" + i).value;
arrDate = strDate.split('/');
month = parseInt(arrDate[0], 10);
day = parseInt(arrDate[1], 10);
year = parseInt(arrDate[2], 10);
if (((Y + 5) * 12 + M < year * 12 + month) || ((Y + 5) * 12 + M === year * 12 + month && D < day)) {
this.getField("Text" + i).fillColor = color.red;
}
}

Date is considering 31 days of month

While working with date difference, when I am using below code somehow function is assuming that all the months have 31 days. For ex. if I am subtracting 01-March with 28-February the difference is coming as 4 days. Is there any simple way to twick this. Any help will be appreciated.
function myFunction()
{
var sysdt = "02/28/2013";
var year = sysdt.substring(6,10);
var mon = sysdt.substring(0,2);
var date = sysdt.substring(3,5);
var n = Date.UTC(year,mon,date);
var userdt = "03/01/2013"
var yr = userdt.substring(6,10);
var mn = userdt.substring(0,2);
var dd = userdt.substring(3,5);
var n1 = Date.UTC(yr,mn,dd);
var x = document.getElementById("demo");
x.innerHTML=(n1-n)/(1000*24*60*60);
}
This will give you the difference between two dates, in milliseconds
var diff = Math.abs(date1 - date2);
example, it'd be
var diff = Math.abs(new Date() - compareDate);
You need to make sure that compareDate is a valid Date object.
Something like this will probably work for you
var diff = Math.abs(new Date() - new Date(dateStr.replace(/-/g,'/')));
i.e. turning "2011-02-07 15:13:06" into new Date('2011/02/07 15:13:06'), which is a format the Date constructor can comprehend.
U can subtract like this--
var d1 = new Date(); //"now"
var d2 = new Date("2011/02/01") // some date
var diff = Math.abs(d1-d2); // difference in milliseconds
var days = diff*24*60*60*1000;
You code is actually subtracting March 1 from April 1, as the months in JavaScript dates are 0-based.
var sysdt = "02/28/2013";
var date1 = new Date(sysdt);
var userdt = "03/01/2013"
var date2 = new Date(userdt);
var days = (date2-date1)/(1000*24*60*60);
or subtract 1 from month in your code
var sysdt = "02/28/2013";
var year = sysdt.substring(6,10);
var mon = sysdt.substring(0,2)-1; // months are from 0 to 11
var date = sysdt.substring(3,5);
var n = Date.UTC(year,mon,date);
var userdt = "03/01/2013"
var yr = userdt.substring(6,10);
var mn = userdt.substring(0,2)-1; // months are from 0 to 11
var dd = userdt.substring(3,5);
var n1 = Date.UTC(yr,mn,dd);
var days = (n1-n)/(1000*24*60*60);

Categories

Resources