why are the dates not being generated properly? - javascript

I am using a function in Angular JS to generate the dates for the past one week starting from today's date. I am storing these dates in an array and then using that array to flood a dropdown.
The following is the code that is being used by me.
generate() {
this.date_new = [];
var date = new Date();
var date1 = new Date();
for (var i = 0; i < 7; i++) {
date.setDate(date1.getDate() - i);
var a = date.toString();
var str = this.convert(a);
this.date_new.push(str);
}
}
Here convert is a function which is being used to convert the dates to the required format. A screenshot of generated dates is attached below.
As evident from the screenshot, the last two dates are incorrect. Can somebody explain to me, what the problem is?

The setDate() method sets the day of the Date object relative to the
beginning of the currently set month.
The above is from MDN.
Your code works for the first 5 dates, but once you are modifying your February date with -1, it sets the day relative to the current month e.g. February. So this will turn into January (as you are setting the day to -1), same happens in the next iteration and you get December.
For an easy fix you can just set the date variable to new Date() in the first line of your for loop.

The issue here is using the same date variable in the loop. You need to re-initialize it.
As can be seen in Parameters Value section in the link here. Zero and negative values in setDate() sets the date from previous month.
Hence at setDate(0), date value is set to last day of Feb. Now since you are using the same variable, setDate(-1) takes the previous month from Feb hence you get Jan.
You need to change the code to something like this:
generate() {
this.date_new = [];
var date1 = new Date();
for (var i = 0; i < 7; i++) {
// re-initialize date
var date = new Date();
date.setDate(date1.getDate() - i);
var a = date.toString();
var str = this.convert(a);
this.date_new.push(str);
}
}
Hope this helps :)

The issue here is that negative numbers inside the setDate method don't work quite well.
Please update the code to something like below:
this.date_new = [];
var date = new Date();
var date1 = new Date();
for (var i = 0; i < 7; i++) {
date= new Date(date1.getFullYear(), date1.getMonth(),date1.getDate()-i);
var a = date.toString();
var str = this.convert(a);
this.date_new.push(str);
}
Hope this will solve your problem.

Related

Trying to dateAdd with Moment.js and getting odd results

I have a very basic loop
console.log(thisStart);
console.log(thisEnd);
console.log(thisDate);
while(checkcounter < 10){
console.log(checkcounter);
thisDate = moment(thisDate,'MM/DD/YYYY').add(1,'days').toDate('MM/DD/YYYY');
console.log(thisDate);
checkcounter++;
}
I would expect that to give me the next day formated MM/DD/YYYY but instead the first iteration IS the next day but then it jumps 6 months.
Being a new moment.js user I am not sure where I am going wrong
The problem is in the statement inside the loop:
thisDate = moment(thisDate,'MM/DD/YYYY').add(1,'days').toDate('MM/DD/YYYY');
The first error is to pass a format string to the moment constructor when the first argument is a Date object. As described here, you need to pass a format string only if the first argument is a string containing a date:
thisDate = moment(thisDate).add(1,'days').toDate('MM/DD/YYYY');
The add invocation is correct but the doDate one is not. The function toDate does not take in input a format string:
thisDate = moment(thisDate).add(1,'days').toDate();
Here the complete snippet of code:
var thisDate = new Date(),
checkcounter = 0;
console.log('Init:', thisDate);
while (checkcounter < 10) {
console.log('Check counter:', checkcounter);
thisDate = moment(thisDate).add(1, 'days').toDate();
console.log('thisDate:', thisDate);
checkcounter++;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.10.6/moment.js"></script>

Iterate through a range of dates in Javascript

For the last few days I was struggling with iterating through a range of dates. I was using following piece of code to test:
var current_date = new Date("2014-08-01");
var end_date = new Date("2014-10-31");
var end_date_time = end_date.getTime();
while (current_date.getTime() <= end_date_time) {
document.write(current_date + '<br>');
current_date.setDate(current_date.getDate()+1);
}
To me it looks correct, but there's a problem. It's missing the last day. I was turning this code around, used a for- loop, defined new Date within loop and all the things you can imagine. One thing stayed the same. Last day missing!
By curiosity I used following format to create the Dates:
var current_date = new Date("08/01/2014");
var end_date = new Date("10/31/2014");
And to my surprise, it worked as expected. Now I'm wondering if this is a normal behaviour or a bug in Date?
I would be thankfull, if someone can enlighten me.
that is because there was a change in time, check that the first days are in GMT Daylight Time and the lasts in (GMT Standard Time)
so your code better to use UTC
var current_date = new Date("2014-08-01");
current_date = new Date(current_date.getUTCFullYear(), current_date.getUTCMonth(), current_date.getUTCDate(), current_date.getUTCHours(), current_date.getUTCMinutes(), current_date.getUTCSeconds());
var end_date = new Date("2014-10-31");
end_date = new Date(end_date.getUTCFullYear(), end_date.getUTCMonth(), end_date.getUTCDate(), end_date.getUTCHours(), end_date.getUTCMinutes(), end_date.getUTCSeconds());
var end_date_time = end_date.getTime();
while (current_date <= end_date) {
document.write(current_date + '<br>');
current_date.setDate(current_date.getDate()+1);
}

new Date() - object is not a function

I'm working in AngularJS, but I'm experiencing an error when working with dates. I currently have one Unix timestamp, and I need to find out if it is today.
var start = new Date();
start.setHours(0,0,0,0);
var end = new Date();
end.setHours(23,59,59,999);
// Convert to Second/Unix Timestamp
start = Math.round(start.getTime() /1000);
end = Math.round(end.getTime() /1000);
for (i = 0; i < list.length; i++) {
var date = Date.utcDateToTimestamp(list[i].date_utc);
if(start < date && end > date)
console.log('this one is today');
}
However, I'm getting an error in the console:
TypeError: object is not a function
I've looked into it, and it seems I can't even create a new Date object without this being thrown:
var start = new Date();
Is this something really obvious, or..?
Maybe look for simple solution:
//Get today's date
var todaysDate = new Date();
//call setHours to take the time out of the comparison
if(inputDate.setHours(0,0,0,0) == todaysDate.setHours(0,0,0,0));
{
//Date equals today's date
}
You don't need to check for hours, reset hours to zero and compare them. You are interested in year, month, day only:)

Comparing dates Java Script

I have the following scenario that I am strugling to code.
I have a valuation date that is a string that is chosen by a user from a calander popup. What I need to do is take that date and pass it into a function that works outs a second date depending on the value of that date. If the first date is more than 7 days from the first day of the month use the first day of the month else use the last day of the month. This needs to happen in client side as this date need to be displayed after they have chosen the first date.
SO far I have the below:
Function CompareDate()
{ var date1 = document.getElementById("textbox1");
var x = new date();
var year = x.getYear();
var day = x.getDay();
var thisMonthFirstDay = new Date(year, month,1)
var thisMonthLastDate = ....
var 1day = 1000*60*60*24
var date1_ms = recdate
var date2ms = thisMonthFirstDay.gettime()
if(Math.round(difference_ms/1day) > 7
{var textbox = document,getelementbyid("textbox2");
textbox.value = texbox.value + thisMonthLastDate
}
else
{
textbox.value = texbox.value + thisMonthFirstDay }
}
Any examples of how this can be done would be greatly appeciated.
Cheers
getDate() will give you the day of month (e.g. 18), so if (getDate() <= 7) { outputDate = 1; } If you're having a problem getting the last day of each month for the else statement, I generally use a 12 capacity array with hard-coded values, adding 1 to February if (year % 4 == 0).
I have managed to resolve this after a finding the parseDate() function on a fiddler site. That allowed me to convert the date from this format (31 Jan 2013) to a date and then I could just use the getDay(function) to see if the day was > 7. From there it was easy!
Thanks for above suggestions.

JS - Compare which date is older

I want to compare two dates as which is bigger in those dates.
var date1 = 2011-9-2;
var date1 = 2011-17-06;
Can anybody say how can I do this?
You'll need to convert both strings to date objects first.
var date1 = new Date('2011-09-02');//yyyy-mm-dd format
var date2 = new Date('2011-06-17');
if(date1 > date2){
alert('date1 is bigger than date2');
}
Once you have the 2 variables as date objects you can compare them against each other (without needing to convert to milliseconds/minutes/?)
Check this link
And then do something like this:
var days = 0;
var difference = 0;
Christmas = new Date("December 25, 2005");
today = new Date();
difference = Christmas - today;
days = Math.round(difference/(1000*60*60*24));
Code source
Create Date objects from your two values (check this link) and use that to do the comparison.

Categories