Get the date between 2 dates using node.js - javascript

In node.js I need to get the date within the date range of particular gap.
Consider two dates:
startDate:2016-07-10T00:00:00.000Z,
payByDate:"13"(13th of every month);
endDate:2016-10-08T00:00:00.000Z
I need an array of dates of monthly or weekly gap between these 2 dates.
My result Should be:(Monthly gap)
[2016-07-13T00:00:00.000Z,
2016-08-13T00:00:00.000Z,
2016-09-13T00:00:00.000Z]
EDIT:
My startdate is 2016-07-10T00:00:00.000Z , so i can calculate the noOfmonths using endDate-startdate, but the array entry should be by payByDate.
I am using MOMENT.JS, but its returning only noOfMonths not the dates. Please share your ideas. Thanks in advance.
Now is it possible to calculate the calculate the Above array.Please note that "payByDate" is string.

you can use getMonth() function to get the month of your date. then keep adding one to it till you reach the end date.
var arrayDates = [];
arrayDates.push(startDate);
var tempDate = new Date(new Date(startDate).setMonth(startDate.getMonth()+1));
while(tempDate < endDate)
{
arrayDates.push(tempDate);
var tempDate = new Date(new Date(tempDate).setMonth(tempDate.getMonth()+1));
}
Abouve logic will work for monthly gap. to get array of weekly gap, use getDate() function and keep adding 7 to it till you reach the end Date

Try using the manipulate method in moment.js to add a month to the starting date until you reach the second date.
Consider this code. Assuming that the first date and the last date are already moments when they are passed into this function, you can use the diff and manipulate methods to create an array of dates by month in between the two different dates:
EDIT:
function monthsBetween(payByDate, startDate, lastDate) {
var months = [];
//finds nearest date to the start date that is on the payByDate
var currentDate = startDate.date(parseInt(payByDate));
//checks if the date is after the startDate and adds a month if it is
if(!currentDate.isSameOrAfter(startDate)){
currentDate = currentDate.add(1, 'months');
}
while (currentDate.isSameOrBefore(lastDate)) {
months.push(currentDate);
currentDate = currentDate.add(1, 'months');
}
return months;
}

Related

I need to get all the dates between any two dates in JavaScript

Using this code I am getting the dates excluding the start dates
var startdate = new Date("");
var enddate = new Date("");
while (startdate < enddate) {
startdate.setDate(startdate.getDate() + 1);
dates.push(new Date(startdate).format("mm/dd/yyyy"));
}
You should replace new Date(startdate) with new Date(startdate.getTime()) to avoid JS error. However, you cannot simply format JS Date object with format(), as this function does not exist, you have to extract year, month, day by yourself. If you want to do it, beware the month value is started from zero.
Please consider using a library like Moment.js instead, it is a lot handy to manipulate date, time and duration.
You can't simply format javascript date using format function, which doesn't exists. You need to split date, month, year and join. Here it may help-
var startdate = new Date();
var enddate = new Date("2019, 10, 23");
while (startdate < enddate) {
startdate.setDate(startdate.getDate() + 1);
dates.push(startdate.getMonth()+1+"/"+startdate.getDate()+"/"+startdate.getFullYear());
}
You have to increase moth by 1 startdate.getMonth()+1 because month starts from 0 in JS.
Consider using Moment.js which has lots of facility.

Calculate departure day based on arrival date and duration of program

Learning examples in comments of E&P Plugin for WordPress
I found a few bugs myself, but still can't make the code work.
Case: Choose Arrival date (date-picker) and program duration from select field (5|7|14|30|60) in days. Generate Departure date
This code from plugin owner don't word at all
jQuery(document).ready(function(){
jQuery('[data-title="Departure"]').on('change',checkDates);
jQuery('[data-title="Program"]').on('change',checkDates);
});
function checkDates(){
var nbDays = jQuery('[data-title="Program"] option:selected').attr('data-price');
var startDate = moment(jQuery('[data-title="Arrival"]').datetimepicker('getDate'));
var endDate = startDate.subtract(nbDays,'days');
jQuery('[data-title="Departure"]').datetimepicker('setDate',endDate.toDate());
}
From first view I find that he use subtract instead of add
I using https://momentjs.com/docs/ and Format date and Subtract days using Moment.js
var startdate = moment();
startdate = startdate.subtract(1, "days");
is equal
var startdate = moment().subtract(1, "days");
So this is mine version:
jQuery(document).ready(function(){
jQuery('[data-title="Arrival"]').on('change',checkDates);
jQuery('[data-title="Program"]').on('change',checkDates);
});
function checkDates(){
var nbDays = jQuery('[data-title="Program"] option:selected').attr('data-price');
var startDate = moment(jQuery('[data-title="Arrival"]').datetimepicker('getDate'));
var endDate = moment().add(nbDays,'days');
jQuery('[data-title="Departure"]').datetimepicker('setDate',endDate.toDate());
}
Still not recalculate departure date on.click and count days not properly
I think you get a wrong end-date because you are doing moment().add(...) which gets the current date at the script execution (equelevant of Date.now()).
Try to use the startDate variable and using moment prototype add on that instead:
var endDate = startDate.add(nbDays,'days');
This will make moment add additional days to the startDate instead of the current date.
End result:
function checkDates(){
var nbDays = jQuery('[data-title="Program"] option:selected').attr('data-price');
var startDate = moment(jQuery('[data-title="Arrival"]').datetimepicker('getDate'));
var endDate = startDate.add(nbDays,'days');
jQuery('[data-title="Departure"]').datetimepicker('setDate',endDate.toDate());
}

moment.js get array of all dates for day of week, week of month between date 1 and date 2

I need to write a javascript function (which we will call getMonthly) which takes in two dates (which are unix timestamps) startDate and endDate, as well as n and w.
This function will return an array of all dates (formatted with helper function) that are nth day of week, wth week of month within this given range.
lets say we have this...
//vars
var startDate = 1478191315; // 11/3/2016
var endDate = 1485993600; // 2/2/2017
var n = 6; // aka saturday
var w = 2; // aka week 2
//helper func to format into parsable date
function formatDate(date) {
return moment.unix(date).format("MM-DD-YYYY");
}
then calling the function I need...
getMonthly(startDate, endDate, n, w);
would return an array...
["11-13-2016","12-11-2016", "1-8-2017"]
I see no simple way to do this, is there a simple way to do this with momentjs, or perhaps a different library that will do this efficiently?

Javascript Date Comparison not behaving as expected

I am getting a SQL date - NOT datetime - object pushed into my Javascript code, and I need to see whether it's before today or not. Here is the code I have (the relevant part):
todaysDate = new Date();
todaysDate.setHours(0,0,0,0);
var date = Date.parse(row[3]);
// date.setHours(0,0,0,0);
if (date < todaysDate) {
alert("date is before today");
dueDate = '<small class="text-danger">';
} else {
alert("date is after today");
dueDate = '<small class="text-muted">';
}
row[3] is the source of the SQL date. So, this works fine for everything except dates that are today. Without the commented line, it thinks that anything with today's date is in the past. With the commented line, my code breaks. Any thoughts as to how to fix this? Not sure what I'm doing wrong.
Thanks!
If your date string is like "2016-04-10" and your time zone is west of GMT, say -04:00, then in browsers compliant with ECMAScript 2016 you will get a Date for "2016-04-09T19:00:00-0400".
When you create a Date using new Date() and set the hours to zero (assuming it's 10 April where you are), you'll get a Date for "2016-04-10T00:00:00-0400".
So when compared they have different time values.
What you need is to either treat the string you get from the database as local, or get the UCT date where you are, so:
var dateString = '2016-04-10';
var parsedDate = new Date(dateString);
var todayUTCDate = new Date();
todayUTCDate.setUTCHours(0,0,0,0);
document.write(parsedDate + '<br>' + todayUTCDate);
But not all browsers parse strings according to ECMAScript 2015 so they should always be manually parsed. Use a library, or write a small function, e.g.
// Parse date string in format 'yyyy-mm-dd' as local date
function parseISOLocal(s) {
var b = s.split(/\D/);
return new Date(b[0], b[1]-1, b[2]);
}
and replace:
var date = Date.parse(row[3]);
with:
var date = parseISOLocal(row[3]);
and then in the comparison, compare the time values:
if (+date < +todaysDate) {
or
if (date.getTime() < todaysDate.getTime()) {
Use getTime() of date object.
The getTime() method returns the number of milliseconds between midnight of January 1, 1970 and the specified date.
You can compare miliseconds and do your operations
date.getTime() > todaysDate.getTime()
Also be sure that Date.parse is returning a valid date.

Extract Month and Day in Javascript

I have the date in this format: 1347564203.713372
And need to end up with 2 variables, one that is the month from that date and another that is the day from that date.
How do I do this using Javascript/jQuery?
This should do:
var myDate = 1347564203.713372;
var d= new Date(myDate*1000);
var month = d.getMonth();
var day = d.getDate();
Create a Date object, use setTime to put your timestamp in there, then get the relevant parts:
var d = new Date(), t = 1347564203.713372;
d.setTime(t*1000); // JS uses timestamps in milliseconds
alert(d.getUTCDate());
alert(["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"][d.getUTCMonth()]);
Note use of getUTC* functions - this helps avoid timezone issues and DST.

Categories

Resources