javascript + define dates for each quarter - javascript

I have a dropdown on my page named Quarter which has following values -
Quarter 1
Quarter 2
Quarter 3
Quarter 4
Also i have another field named Year with Year values - 2015,2016,2-17,2-18,2019,2020
I want to define the values for each quarter in my javascript code like
if(quarter = "quarter 1")
{
startdate = 2017-01-01;enddate = 2017-01-31
}
And so on for other quarters as well.
I would like to ask if there is built-in functionality to get the startdate and enddate for each quarter and i will append the year field value to it.so that it does not remain static.
Any help would be appreciated.
Thanks in Advance

Quarter of a financial year starts on April 1 for many countries, so I would argue that you need to set the start of quarter 1 first.
Let's say
var startDate = new Date();
date.setMonth(2);
date.setDate(1);
Then you can have functions like
function addQuarter(date)
{
date.setMonth( date.getMonth() + 3 );
return date;
}
For example
addQuarter(date); //returns Thu Jun 01 2017
Similarly to get last date of quarter
function lastDateOfQuarter( date )
{
date.setMonth( date.getMonth() + 3 );
date.setDate( date.getDate() - 1);
return date;
}
You can format the date as per your requirements for display
function formatDate( date )
{
return date.getDate() + "-" + ( date.getMonth() + 1 ) + "-" + date.getFullYear();
}

I would like to ask if there is built-in functionality to get the startdate and enddate for each quarter and i will append the year field value to it.
Those are constants. Given your example for Q1, you're talking about the normal calendar quarters of a year. Q1 starts on 01/01 and ends on 31/03, Q2 starts on 01/04 and ends on 30/06, etc. Since no quarter starts or ends on the last day of February, this is not a moving target.
No, there's no built-in functionality, but you don't need any. Just construct dates from those constant month and day values and the year you need.
var q1 = {
start: new Date(2017, 0, 1), // Remember, January = 0 here
end: new Date(2017, 2, 31)
};
// ...
Or for UTC:
var q1 = {
start: new Date(Date.UTC(2017, 0, 1)),
end: new Date(Date.UTC(2017, 2, 31))
};
// ...

//if you are using current year
var todayDate=new Date();
var startMonth=todayDate.getMonth();
var startDay=1;
var endMonth=todayDate.getMonth();
var endtDay=31;
switch(quarterValue){
case "Q1" : startMonth=0;endMonth=2;
case "Q2" : startMonth=3;endMonth=5;
case "Q3" : startMonth=6;endMonth=8;
case "Q4" : startMonth=9;endMonth=11;
}
todayDate.setMonth(startMonth);
todayDate.setDate(startDay);
var startDate=todayDate;
todayDate.setMonth(endMonth);
todayDate.setDate(endDay);
var endDate=todayDate;

Related

Given the current date, how to get the last day of the last 24 months?

Regards,
Given the current date, I would like to know the last day of the month for the last 24 months. Im trying to get an output similar to this:
30/11/2018 for current month -1
31/10/2018 for current month -2
...
31/12/2016 for current month -24
I've tried searching trough SO but I couldn't find a similar question.
Any help? :)
Edit: Based on Jalees code, I've come with this code, that I think it does what I need:
for(i=0;i<24;i++)
{
d = new Date();
d.setMonth(d.getMonth() + (1 - (i + 1)));
d.setDate(0);
$('#aaaaa').append($('<option>', {value: 'x', text: d.getDate() + '/' + (((d.getMonth() + 1).length == 1) ? '0'+''+(d.getMonth() + 1) : d.getMonth() + 1) + '/' + d.getFullYear()}));
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="aaaaa"></select>
Use loop index to subtract from current month to build a new date for each month and set the day to zero to get last day of prior month
Example using Array#from():
const curr = new Date();
function getPrevMonth(_,i){
const prev = new Date(curr.getFullYear(), curr.getMonth()-i, 0)
return [prev.getDate(), prev.getMonth()+1, prev.getFullYear()].join('/')// format as desired
}
const months = Array.from({length:24}, getPrevMonth);
console.log(months)
you can use this technique
. for month February you can use 1 and for March 2 and continue.
var month = 0; // January
var d = new Date(2008, month + 1, 0);
alert(d); // last day in January

JS Specific ending date calculator

If I have a starting date of 31st of January and I add 1 month, it returns a date of 2nd of March.
I am trying to make a script that will add months to date in this way :
starting date : 31/01/2000
+1 month = 29/02/2000
+2 months = 31/03/2000
+3 months = 30/04/2000
....
+12 months = 28/02/2001
Another case :
Starting date : 28/02/2001
+1 month : 31/03/2001
+2 months : 30/04/2001
...
So, the idea is if starting date is the last day of the current month, ending date must be the last day of month.
So, my code logic is below :
var date = new Date(2017,01,30);
1. Get current day of this date. (x)
2. If x < days in this month, add 1 month to date
2.1 In same if, If modified date < x, set date to last day of previous month
3. Else of main if, set date to last day of next month
My JSFiddle is here : https://jsfiddle.net/5mfLo8zs/
Idk what is wrong in syntax, but it gives me a .getDate() is not a function error, probably, it's not the unique problem.
P.S. I know that this theme is duplicated, I took 10 minutes to search for identic question, but I found just how to set last day of month, but here I need something more.
You can try something like this:
Logic:
Check if date passed is the last day of the month?
If yes, you will need to add 1 to months. This is because, logic to get last day of month works by creating a date as 1st day of next month and then subtract 1.
Now initialize a temp variable that will hold value of day. Set it to 0 by default.
If months are same, set this temp variable to passed date's day. Else let it be 0.
Now you have all the parameters to create new date. Return it. Note, updating same date variable will override original value. So try to avoid any manipulations to it.
function addMonths(date, months) {
var d = 0;
var next = new Date(date.getFullYear(), date.getMonth(), date.getDate() + 1);
if (next.getMonth() === date.getMonth()) {
d = date.getDate()
}
else{
months++
}
// use following line in actual code.
// return new Date(date.getFullYear(), date.getMonth() + months, d)
// This line is just fror demonstration purpose.
return new Date(date.getFullYear(), date.getMonth() + months, d).toDateString();
}
console.log(addMonths(new Date(2017, 0, 31), 1));
console.log(addMonths(new Date(2017, 0, 31), 3));
console.log(addMonths(new Date(2017, 0, 15), 3));
console.log(addMonths(new Date(2016, 11, 31), 1));
console.log(addMonths(new Date(2016, 11, 11), 1));

Pikaday date range don't work

I used the range function from pikaday.
with onSelectI set the date range what actually works.
Here is my example:
onSelect: function(date) {
var first_ = (date.getDate() - date.getDay())+1;
var last_ = first_ + 4;
var firstday = new Date(date.setDate(first_));
var lastday = new Date(date.setDate(last_));
picker.setStartRange(firstday);
picker.setEndRange(lastday);
picker.draw();
var f_startdate = firstday.getDate()+'.'+(firstday.getMonth()+1)+'.'+firstday.getFullYear();
var f_enddate = lastday.getDate()+'.'+(lastday.getMonth()+1)+'.'+lastday.getFullYear();
var kw = getWeekNumber(date.getFullYear()+'/'+(date.getMonth()+1)+'/'+date.getDate());
document.getElementById('calendar').value = f_startdate+' - '+f_enddate;
// document.getElementById('calendar').value = 'KW: '+(kw+1);
}
But when I select the 03.06.2016 the range is set to the "30.05.2016 - 03.05.2016" and the Input is wrong. Maybe anyone can help me.
Here is a working example: https://jsfiddle.net/24aL9f21/1/
Your issue is here:
var first_ = (date.getDate() - date.getDay())+1;
That gives you the date of the previous Monday, but also goes negative. 3 June is a Friday (day number 5), so first_ is set to:
3 - 5 + 1 = -1
Then:
var last_ = first_ + 4;
so last_ is set to 3. Now when you do:
var firstday = new Date(date.setDate(first_));
you are actually setting date to a date of -1, which is one before the start of the month so 30 May. setDate returns the time value, so firstday is a new Date instance set to 30 May also.
Then:
var lastday = new Date(date.setDate(last_));
you are setting date to 3 May (remembering that in the line above you set it to 30 May). Again, the setDate method returns the time value, so a new Date object is created for that date. So you get dates for 30 May and 3 May (and if you check date, you'll set it's also 3 May).
QED (which my Mathematics teacher told me was "Quite Easily Done"). ;-)
So your code for the Monday is fine. If you want to get the date for the following Friday, just do:
var lastday = date.setDate(date.getDate() + 4);
Here lastday and date will reference the same Date object, but creating another copy doesn't seem useful.

How do I roll a date forward to a specified day in Javascript?

I'm working on a form that needs to automatically calculate the day the form is being submitted in the format ('MMDDYYYY'), and then on the click of one of two links a link, calculate the closest first day of the coming month, and the closest 15th day of the coming month.
I already created a script that pulls in the date and outputs it to a variable in the format I need, but I need help in calculating the roll forward.
Here's an example of the logic I'm thinking I need:
If the current date is 04092013, on a the button press labeled "Coming 1st of Month" a variable value of 05012013 would be calculated.
If the current date is 04092013, on a button press labeled "Coming 15th of Month" a variable value of 04152013 would be calculated.
If the current date is 04162013 or any date up to the end of the current month, on a button press labeled "Coming 15th of Month" a variable value of 05152013 would be calculated.
Look at the Date object, it should provide what you need:
https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Date
For example something like this for your first 2 buttons:
$(function() {
var date = new Date(2013, 10, 24);
$("#date").html(date.toString());
$("#date1").html((new Date(date.getYear(), date.getMonth()+1, 1)).toString());
$("#date2").html((new Date(date.getYear(), date.getMonth()+1, 15)).toString());
});
(Though I'm sure there are easier ways to do this if you look through the Date documenation)
Here is an example. If you want it back as a string, you'll have to format it at the end as desired (work with UTC ).
If you put in a date that has the same day number as you're asking of it, it returns the same day, not moving forwards a month.
var date_string = '04092013';
// MMDDYYYY
function nextNthOfMonth(date_string, n) {
var date;
// n to Int, default 1
n = (+n || 1);
// date_string to ISO 8601
date_string = // "yyyy-MM-ddTHH:mm:ssZ"
date_string.slice(4)
+ '-' + date_string.slice(0, 2)
+ '-' + date_string.slice(2, 4)
+ 'T00:00:00Z';
// construct date object
date = new Date(date_string);
// fix to desired date
if (n < date.getUTCDate()) { // adjust for month if req.
date.setUTCMonth(date.getUTCMonth() + 1);
}
date.setUTCDate(n);
return date; // or format as desired
}
nextNthOfMonth(date_string, 1);
// Wed May 01 2013 01:00:00 GMT+0100 (GMT Daylight Time)
nextNthOfMonth(date_string, 15);
// Mon Apr 15 2013 01:00:00 GMT+0100 (GMT Daylight Time)
Since you know the format of your date, split the input into parts:
var dateStr = '04092013'
var month = dateStr.substr(0,2);
var day = dateStr.substr(2,2);
var year = dateStr.substr(4,4);
The construct a new date base on the rule you want to set:
var newDate;
switch(rule)
{
case 'rule1':
newDate = new Date(year, month, 1);//first month is 0
break;
case 'rule2':
newDate = new Date(year, month, 15);//first month is 0
break;
}
remember to check if the day is greater that 15.
Try
function getDate() {
var s = document.getElementById('date').value;
if(s){
return new Date(s.substring(4), parseInt(s.substring(2, 4), 10) - 1, s.substring(0, 2))
}
}
function comingDate(date, day){
date = new Date(date);
var cday = date.getDate();
date.setDate(day);
if(cday >= day){
date.setMonth(date.getMonth() + 1)
}
return date
}
function f15(){
var d = getDate();
var next = comingDate(d, 15);
console.log(next)
}
function f1(){
var d = getDate();
var next = comingDate(d, 1);
console.log(next)
}
Demo: Fiddle

Using Javascript to automatically adjust date to 2nd Saturday of every month?

I need Javascript code for a website to automatically adjust a date. The goal is to have the code automatically adjust the following statement to be the second Saturday of every month from now until eternity:
Next membership meeting: Saturday, MONTH, DAY, YEAR 11 a.m. to noon.
Anyone have an idea? Much appreciated!
This function will get you the date object, you can pull out what you need from it:
var getMeeting = function(year, month){
var date = new Date(year, month, 1, 0, 0, 0, 0);
date.setDate(14-date.getDay());
return date;
};
alert(getMeeting(2011,5));
I didn't test but here is the basics:
//our main code
var Months = ["Jan", "Feb", "Mar", /*... you finish... */ ];
var meetingDate = getMonthlyMeeting();
document.Write( "<i>Next membership meeting:</i> Saturday, " + Months[meetingDate.getMonth()] + ", " + meetingDate.getDay() + ", " + meetingDate.getYear() + " 11 a.m. to noon.");
// call this to get the monthly meeting date
// returns a Date() object
function getMonthlyMeeting(){
var today = new Date(); //JS automatically initializes new Date()s to the current time
//first, see if today is our meeting day
var meetingDate;
var thisMonthsMeeting = getSecondTuesdayInMonth(today.getMonth(), today.getYear());
if( thisMonthsMeeting.getDay() == today.getDay() ){
// today is our meeting day!
meetingDate = today;
}
else {
if ( today.getDay() < thisMonthsMeeting.getDay() ){
// it hasn't happened this month yet
meetingDate = thisMonthsMeeting;
} else {
//this month's meeting day has already passed
if( today.getMonth() == 11 ){
// rolling over to the next year
meetingDate = getSecondTuesdayInMonth(0, today.getYear() + 1);
} else {
meetingDate = getSecondTuesdayInMonth(today.getMonth() + 1, today.getYear());
}
}
}
return meetingDate;
}
// this is a helper function to get the second tuesday in any month
// returns a Date() object
function getSecondTuesdayInMonth(var month, var year){
var saturdays = 0;
var testDay= new Date();
while( testDay.getDay() != 2 && saturdays < 2 ){
//while the day we are testing isnt tuesday (2) and we haven't found it twice
if( testDay.getDay() == 2 )
saturdays = saturdays + 1; //we found a saturday
testDay= new Date(testDay.getTime() + 86400000); //increment our day to the next day
}
//when we finish the while loop, we are on our day
return testDay;
}
So, I figure that the meat of your problem is: How do I know what the second saturday of each month is?
Not tested, but this is what I came up with:
It is abstracted for any nth day of any month.
nthDate = function(nth_week, nth_day, month){
var src_date = new Date();
src_date.setDate(1);
src_date.setMonth(month);
return ( (nth_week * 7) - src_date.getDay() ) - ( Math.abs( nth_day - 6) );
};
var cur_date = new Date();
var cur_day = cur_date.getDay();
//2 for the 2nd week of the month
//6 is the integer value for saturday (days of the week 0-6)
var nth_date = nthDate( 2, 6, cur_date.getMonth() );
if(cur_day < nth_date){
//display the upcoming date here
}else if( cur_day > nth_date){
//figure out next month's date and display that
var next_date = nthDate(2, 6, (cur_date.getMonth() +1) );
//does this deal with the case of the month being december?? not sure.
}
The 2nd week is in the range of 14 days into the month.
We can:
first subtract the offset for the day of the week that this month starts with,
then second:
we can subtract the offset for the day of the week that we are looking for.
(this needs to be the offset of days, so saturday is a 0 (zero) offset. We get this value from the absolute value of nth day minus the number of days in the week.
This gives us the date of the second saturday.
Then, because you have some ints you can do a simple compare against the values.
If we're before the second saturday, display that, if not calculate a new date for next month.
Hope that helps.

Categories