Reducing dates not working in javascript - javascript

Trying to work out how I can get 10 days preceding current date in a select box, populated using ng-option. This is the code for reducing dates
var n = 1;
var d = new Date();
var dateList = [];
while (n < 10) {
d.setDate(d.getDate() - n);
dateList.push(d);
n++;
}
console.log(dateList);
I have swapped n for 1 or any number, but for some reason, I only get the same date gets repeated 10 times.
Many thanks in advance

Because you push the same date nine times and mutate that in the loop. You want to get 9 different date objects, which you can easily clone as:
dateList.push(new Date(d));

dayinms = 86400000
da = [];
for (i=1;i<=10;i++) {
d= new Date()
d.setTime(d.getTime() - (dayinms * i))
ds = d.getDate() + '/' + d.getMonth() + '/' + d.getFullYear()
da[i-1]=ds
}
console.log(da)

Related

How to get days between date range by using javascript or jquery

In a form, I define a start date, an end date, and weekdays
Example:
Start date: 2017-02-07
End date: 2017-03-07
Weekdays: Monday and Thursday
Now I want to get all Mondays and Thursdays between start date and end date by using Javascript or jQuery.
Who can help me?
Thanks...
Simple code. Codepen
var startDate = new Date('2017-02-07');
var endDate = new Date('2017-02-17');
var monday = [];
var thursday = [];
for (var d = new Date(startDate); d <= new Date(endDate); d.setDate(d.getDate() + 1)) {
if(d.getDay()==1)
monday.push(d);
else if(d.getDay()==4)
thursday.push(d);
}
You can parse date and iterate over increment 1 day and getDay to map with sun(0) to sat(6)
var startDate = new Date("2017-02-07");
var endDate = new Date("2017-03-07");
var totalMon = [];
var totalThu = [];
for (var i = startDate; i <= endDate; ){
if (i.getDay() == 1){
totalMon.push(i.getFullYear() + "-" + (i.getMonth()+1) + "-" + i.getDate());
}
if (i.getDay() == 4){
totalThu.push(i.getFullYear() + "-" + (i.getMonth()+1) + "-" + i.getDate());
}
i.setTime(i.getTime() + 1000*60*60*24);
}
console.log(totalMon.length ,totalMon);
console.log(totalThu.length ,totalThu);
Below code finds number of Mondays. You can modify it to calculate any day. It basically finds the difference of days in two dates. Divide it by 7 (this is the number of times everyday will come). Now for pending days loop through the dates and check if a desired day comes in this loop.
var startDate = new Date(2017, 02, 07);
var endDate = new Date(2017, 03, 07);
var dayDiff = Math.round((endDate-startDate)/(1000*60*60*24));
var numberOfMondays = Math.floor(dayDiff/7);
var remainingDays = dayDiff%7;
for(i=0;i<remainingDays;i++)
{
var dateObj = new Date();
dateObj.setDate(endDate.getDate() - i);
if(dateObj.getDay() == 2)
numberOfMondays=numberOfMondays+1;
}
alert(numberOfMondays);
PS : the other two answer are looping through all the dates. I will not suggest this. In code above the number of iterations in loop will never exceed 6 irrespective of the difference in dates.

Chart.js :set yAxis point to 0 when there is gap between two dates

I'm using Chart.js and in my xAxis I have an array of some dates with gaps like [2016:08:06,2016:08:10] and their matching values [20,40]
the problem is that Chart.js are displaying days between the given array of dates.
I don't want to set my array to [20,0,0,0,40] since I have a gap of 3 days.
how can I set autoatically their matching values in the yAxis to 0.
I encountered the same problem not long ago and "fixed" it by writing a simple javascript hack.
1. Create new array of dates;
2. Compare it to your current array of dates;
3. Fill the corresponding gaps in your values array with zeroes;
It probably can be done simplier and prettier but here's my code:
var minDate = new Date(date[0]).getTime(),
maxDate = new Date(date[date.length - 1]).getTime();
var newDates = [],
currentDate = minDate,
d;
while (currentDate <= maxDate) {
d = new Date(currentDate);
newDates.push(d.getFullYear() + '-' + ("0" + (d.getMonth() + 1)).slice(-2) + '-' + ("0" + d.getDate()).slice(-2));
currentDate += (24 * 60 * 60 * 1000); // add one day
}
for (var i = 0; i < newDates.length; i++) {
if (newDates[i] == dates[i]) {
newCount.push(count[n]);
n++;
} else {
newCount.push("0");
dates.splice(i, 0, newDates[i]);
}
}

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;
}
}

Javascript function , which takes a month/date and disply 12 months/dates back

Is there any javascript function which takes one input parameter (e.g 04/2014 ) and return
12 months and dates with the same format
(e.g 04/2013.........................................04/2014)
i have this one
function calcFullMonth(startDate) {
//copy the date
var dt = new Date(startDate);
dt.setMonth(dt.getMonth() - 1);
return dt;
}
The logic that i have is this .But it gives me only one month back
I need to get 12 months and 1 year back and display them as you see second e.g.
Thanks
Just call your original function as many times as you need, and store them in an array.
function calcFullMonth(startDate, num) {
var months = [];
for (var i = 0; i < num; i++) {
var dt = new Date(startDate);
dt.setMonth(dt.getMonth() + i);
months[i] = dt;
}
return months;
}
For example, to get the current month until this month next year, use num = 13
console.log(calcFullMonth(new Date(), 13));
fiddle
Try the following function
function Get12MonthBack(input) {
var year = input.split("/")[1];
var month = input.split("/")[0];
var d = new Date(year, month);
d.setMonth(d.getMonth()-12);
return (d.getMonth().toString().length == 1 ? "0" + d.getMonth() : d.getMonth()) + "/" + d.getFullYear();
}
Tests
Get12MonthBack("03/2011")
"03/2010"
Get12MonthBack("11/2012")
"11/2012"

previous quarters in javascript

Forgive me I tried several searches here and other places in general but cant seem to fix issue I am having at the moment. Can someone please help me figure out?
I am trying to find quarter strings from inputdate in JavaScript. For "01/31/2009" it should give Q1,2013 Q4,2012 etc based on offset given as input parameter. when offset is 0 then current quarter, 1 then previous, 2 then previous 2 quarter etc...
my current code: jsfiddle
function getQuarterStrings(id) {
var d = new Date();
var d = new Date("01/31/2009");
var str;
switch (id) {
...
}
Remaining code is in jsfiddle. As you can see, it fails on second last condition even though everything seems ok. Please help me figure out my mistake. Thank you!
Some of your comparisons are off, and Date tries to compensate for months that don't have as many days when you setMonth. This code should work:
function getQuarterStrings(id) {
var d = new Date("03/31/2009");
d.setDate(1);
d.setMonth(d.getMonth() - id * 3);
var month = d.getMonth() + 1;
var year = d.getFullYear();
var quarter = Math.ceil(month / 3);
return ("Q" + quarter + ", " + year);
}
This works, and is a lot more concise. It also allows you to use any offset instead of a limited set of values:
function getQuarterStrings(date, id) {
// quarter is 0-based here
var quarter = Math.floor(date.getMonth() / 3),
year = date.getFullYear();
quarter -= id;
if(quarter < 0) {
var yearsChanged = Math.ceil(-quarter / 4);
year -= yearsChanged;
// Shift quarter back to a nonnegative number
quarter += 4 * yearsChanged;
}
return "Q" + (quarter + 1) + ", " + year;
}
http://jsfiddle.net/dPmf2/6/
You can also get rid of the switch statement by doing this:
function getQuarterStrings(id) {
var d = new Date();
var d = new Date("01/31/2009");
var str;
if (id !== 0){
d.setMonth(d.getMonth() - 3*id);
}
str = getQuarter(d);
return str;
}

Categories

Resources