Trying to dateAdd with Moment.js and getting odd results - javascript

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>

Related

why are the dates not being generated properly?

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.

comparing a date string with current Date()

So, I already have a variable that holds all the cells in a certain column.
each cell contains, as it's innerText, a timestamp formatted like such, yyyy-mm-dd hh:mm in 24h format.
How do I go about comparing the string that I have with Date() to see if the string is within the next hour?
I was thinking a for loop to go through the array with an if function inside saying "if the time shown is within an hour of the current time then change the background color of the cell to red.
for(var i=0; i<column.length;i++){
if(column[i].innerText - Date() < 1hr){ //this line needs work
column[i].style.backgroundColor='#ff000';
} else(){
}
};
I'm sure there probably needs to be some parse method used or something but I'm not too familiar with it.
note: I'm using Tampermonkey to inject the code into a page I have no control over and so the timestamps are as the come.
Date constructor does the job of parsing for you. So something like this would be all you need:
hour = 3600000 //1 hour in ms
nextHour = new Date(column[i].innerText) - new Date()
if(nextHour <= hour && nextHour >= 0) {
//Your code here
}
Explanation:
Since Javascript Date is based on milliseconds since midnight January 1, 1970, - (minus) operator allows you to treat it as a Number and returns the resulting number as a Number.
Change this:
if(column[i].innerText - Date() < 1hr){
To this:
var hourNow = new Date().getHours();
var hourColumn = Number(column[].innerText.split("")[11] + "" + column[].innerText.split("")[12]);
if (hourNow + 1 >= hourColumn || hourColumn + 1 <= hourNow) {
And it should work.
You can go with below approach. Here I have used getUTCHours(), because new Date(new Date(columns[i].innerText) - new Date()) will give UTC timestamp. You can find the explanation about UTC timestamp from here
var columns;
function changecolors() {
columns = document.getElementsByClassName('column');
for (var i = 0; i < columns.length; i++) {
if (new Date(new Date(columns[i].innerText) - new Date()).getUTCHours() < 1) {
columns[i].style.backgroundColor = '#ff0000';
}
};
}
<div class="column">2018-11-18 09:30</div>
<div class="column">2018-11-18 11:00</div>
<button onclick="changecolors()">Change Colors</button>

Javascript Comparing Time not working

I am trying to check if a specific ISO DateTime is before 18:00
This is the simple code:
// Define the date I want to check
var targetDate = "2015-02-04T13:30:00Z";
// Parse the string into a date object
var target = new Date.parse(targetDate);
// Compare the target date againt a new date object set to 18:00:00
if(target < new Date().setHours(18 , 0, 0)){
console.log("BEFORE");
} else {
console.log("AFTER");
}
even though the time in my targetDate is set to 13:30:00 the output is always AFTER.
I have search how to compare times, and from the results I found, a simple comparison as I did should work.
I would really appreciate it if someone could point out what I am doing wrong.
Testing the code gives the following error:
Uncaught TypeError: function parse() { [native code] } is not a constructor
This is because of the "new" keyword. Removing this fixes your problem:
// Define the date I want to check
var targetDate = "2015-02-04T19:30:00Z";
// Parse the string into a date object
var target = Date.parse(targetDate);
// Compare the target date againt a new date object set to 18:00:00
if (target < new Date().setHours(18, 0, 0)) {
console.log("BEFORE");
} else {
console.log("AFTER");
}
when you try to parse the target data, you don't have to use the new keyword.
Here's an working JSFiddle;
The code:
// Define the date I want to check
var targetDate = "2015-02-04T13:30:00Z";
// Parse the string into a date object
var target = Date.parse(targetDate);
// Compare the target date againt a new date object set to 18:00:00
if (target < new Date().setHours(18, 0, 0)) {
alert("BEFORE");
} else {
alert("AFTER");
}
Try:
var targetDate = new Date("2015-02-04T13:30:00Z");
var numHours = targetDate.getHours();
if (numHours < 18) {
console.log("BEFORE");
} else {
console.log("AFTER");
}
If you can count on the ISO format and don't want to convert it to local time
you can just look at the hours substring.
var targetDate = "2015-02-04T13:30:00Z";
var isbefore18=targetDate.substring(11,13)-18<0;
isbefore18 /* value: (Boolean) true */
David P has the correct answer. A Date() is composed of a date part, and a time part
new Date().setHours(18,0,0)
creates a Date at 18:00 today, which will always be greater than 17:30 February 4, 2015, unless you have a time machine.
targetDate.getHours()
Returns the hour value of the time part, which it sounds like you are looking for.

JavaScript validation for datetime combination comparing

I have two dates i want to throw an alert if astart date is less than enddate
format i use dd/mm/yyyy
time 24 hrs format :HH:MM:SS
var strt_date = 31/03/2014 23:02:01;
var end_date = 01/04/2014 05:02:05;
if(Date.parse(strt_date) < Date.parse(end_date))
{
alert("End datetime Cannot Be Less Than start dateime");
return false;
}
See the following answer: Compare two dates with JavaScript
Essentially you create two date objects and you can compare them.
var start_date = new Date('31/03/2014 23:02:01');
var end_date = new Date('31/03/2014 23:02:01');
if (end_date < start_date) {
alert("End datetime Cannot Be Less Than start dateime");
return false;
}
(from reading the linked answer it is possible using the Date::gettime method for comparison purposes may be faster than the actual comparing of date objects)
Your timestamps are not quoted as strings, which is throwing a syntax error, add single quotes to them:
var strt_date = '31/03/2014 23:02:01';
var end_date = '01/04/2014 05:02:05';
if((new Date(strt_date)).getTime() < (new Date(end_date)).getTime())
{
alert("End datetime Cannot Be Less Than start dateime");
return false;
}
Using .getTime() will compare as numbers, so you can determine if the start date has a greater number than the end date.
DEMO
Try to use the folowing format: Date.parse("YEAR-MONTH-DAYTHOURS:MINUTES:SECONDS")
var strt_date = "2014-03-31T23:02:01";
var end_date = "2014-04-01T05:02:05";
if(Date.parse(strt_date) < Date.parse(end_date))
{
alert("End datetime Cannot Be Less Than start dateime");
return false;
}

Calculating Date difference and matching it with array

Is there any way in JavaScript that I can check if date is between 2 dates?
I have an array like
var unavailableDates = ["5-7-2011","6-7-2011","7-7-2011","15-7-2011","16-7-2011","17-7-2011" ];
and now I have 2 dates like 1-7-2011 and 10-7-2011. I want to see if any value from unavailableDates falls between these date. If it falls it should return alert.
Can someone help me on this? I am in process of learning more about JavaScript and jQuery. I am not able to code it the way I understood the problem.
Here you have the solution
var unavailableDates = ["5-7-2011","6-7-2011","7-7-2011","15-7-2011","16-7-2011","17-7-2011" ];
function str2date(sdate){ //This function gets a string and return a Date object
var parts = sdate.split("-");
return new Date(parts[2], parseInt(parts[1], 10)-1, parts[0]);
}
var stamp1 = str2date("1-7-2011").getTime(); //First date. getTime() converts it to an integer
var stamp2 = str2date("10-7-2011").getTime(); //Second date
for(var i=0; i<unavailableDates.length; i++){
var curStamp = str2date(unavailableDates[i]).getTime();
if(curStamp >= stamp1 && curStamp <= stamp2) //Check if it falls in range
alert(unavailableDates[i] + " falls in range");
}
Hope this helps. Cheers
Date object in JavaScript allows compare operation, you only required to have proper Date objects. Create Date objects from your bounds and array members and compare them in a loop.
More information about Date object could be found there: http://www.w3schools.com/js/js_obj_date.asp

Categories