Results between two dates - javascript

I would like to display the difference between two dates:
date_debut<input type="text"name="date_debut" id="datepicker">
</br>
date fin<input type="text"name="date_fin"id="datepicker2">
</br>
nombre jour <input type="text"name="nombre_jour">
</br>
I want to enter the date start and end date and affect me in the number of days - the difference of two dates.
I made a small script, but it does not work. I'm a beginner to JavaScript and I had no time to learn JavaScript.
Here is the script I have made:
$('#datepicker, #datepicker2').datepicker();
$('button').click(function () {
var start = $('#datepicker').val(),
end = $('#datepicker2').val();
var diffInDays = moment(end).diff(moment(start), 'days');
alert(diffInDays);
});

According to Comparing Datepicker Dates Javascript, use .datepicker("getDate") instead of .val() to get the date and then it should just be:
var days = (end - start) / (86400 * 1000)

Related

Convert string to date and alter that date

Good day, I am generating 3 dates from a string, I hope the output was:
billing date: 2020/01/11
cutoff start: 2019/11/11
cuttof end: 2019/12/10
but I get the following:
billing date: 2020/11/10
cutoff start: 2019/11/10
cuttof end: 2019/12/10
I would like to know how javascript works with variables or what is the problem since everything is altered
var month = "Jan-20"
var coverage_month_obj = moment(month, 'MMM-YY').toDate();
var billing_date = new Date(coverage_month_obj.setDate(coverage_month_obj.getDate() + 10))
var cutoff_end = new Date(billing_date.setMonth(billing_date.getMonth() - 1))
cutoff_end = new Date(billing_date.setDate(billing_date.getDate() - 1))
var cutoff_start = new Date(billing_date.setMonth(billing_date.getMonth() - 1))
I would like to know how javascript works with variables or what is the problem since everything is altered
Put simply, calling setXXX on a javascript date variable updates that variable in place. ie, it is what we would call "mutable". You might have assumed dates were immutable and did not change in place.
To answer on a better way to achieve your goal, I'd suggest using the other functionality of momentjs to calculate your 3 dates from the given input string.
var month = "Jan-20"
var coverage_month = moment(month, 'MMM-YY');
//Jan-20 I need to convert it into date format and that the day is 11 (2020/01/11) cutoff start, are two months less from that date (2020/11/11) and cutoff end is one month less from Jan-20, but ends on day 10 (2020/12/10)
var billing_date = coverage_month.clone().add(10, 'days');
var cutoff_start = billing_date.clone().subtract(2, 'months');
var cutoff_end = billing_date.clone().subtract(1,'months').subtract(1,'day')
console.log("billing_date",billing_date);
console.log('cutoff_start',cutoff_start);
console.log('cutoff_end',cutoff_end);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>

Get the date between 2 dates using node.js

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

Difference (in days) between two days in yyyy-mm-dd format?

Sorry if this has been asked before, but I haven't been able to find anything. Here's essentially what I'm trying to do:
new Date(response.departureDate).getTime() - new Date(response.arrivalDate).getTime()
I need to calculate the total number of days (will always be a whole integer) between an arrival and departure date. These dates are strings, structured as 'YYYY-MM-DD'.
How do I go about this?
You can use regexp OR a much simpler approach would be to become familiar with MomentJS API that lets you deal with dates in JS very smoothly (works in Node and browser)
http://momentjs.com/
It does add another tool to your toolbox, but as soon as you are manipulating dates, it is definetely worth it IMHO.
Way to go with MomentJS :
var depDate = moment(response.departureDate);
var arrDate = moment(response.arrivalDate);
var nbDays = depDate.diff(arrDate, 'days');
Look at the Miles' answer here
Just change it to:
function parseDate(str) {
var mdy = str.split('-')
return new Date(mdy[2], mdy[0]-1, mdy[1]);
}
function daydiff(first, second) {
return Math.round((second-first)/(1000*60*60*24));
}
and use:
daydiff(parseDate(response.departureDate), parseDate(response.arrivalDate));
You can use RegEx to change them.
new Date(response.departureDate.replace(/-/g, "/")).getTime()
- new Date(response.arrivalDate.replace(/-/g, "/")).getTime()
So the RegEx .replace(/-/g, "/") will replace all the - to /, and JavaScript will be able to read it right.
I hope this example help for you
Apart from .diff(), you could also use moment durations: http://momentjs.com/docs/#/durations/
Example Fiddle: https://jsfiddle.net/abhitalks/md4jte5d/
Example Snippet:
$("#btn").on('click', function(e) {
var fromDate = $('#fromDate').val(),
toDate = $('#toDate').val(),
from, to, druation;
from = moment(fromDate, 'YYYY-MM-DD'); // format in which you have the date
to = moment(toDate, 'YYYY-MM-DD'); // format in which you have the date
/* using duration */
duration = moment.duration(to.diff(from)).days(); // you may use duration
/* using diff */
//duration = to.diff(from, 'days') // alternatively you may use diff
/* show the result */
$('#result').text(duration + ' days');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.11.1/moment.min.js"></script>
From: <input id="fromDate" type='date' />
To: <input id="toDate" type='date' />
<button id="btn">Submit</button><hr />
<p id="result"></p>
You can use something like this
function countDays(date1, date2)
{
var one_day=1000*60*60*24;
return Math.ceil((date1.getTime()- date2.getTime()) /one_day);
}
countDays(new Date(response.departureDate), new Date(response.arrivalDate));

date difference in days in javascript?

I know how to use javascript, but i have no in depth knowledge of it. I know how I can get the date difference in days in PHP but in this case, I need javascript solution. Honestly, i don't even know if it is possible, to do this with Javascript. I guess that it is,but that is just a guess.
Here is the html that I have:
<div class="span3" id="checkin">
<span class="text-label"><i class="icon-calendar"></i>Check In</span>
<input type="text" name="checkin" value="02/08/2014">
</div>
<div class="span3" id="checkout">
<span class="text-label"><i class="icon-calendar"></i>Check Out</span>
<input type="text" name="checkout" value="04/08/2014">
</div>
Those two fields are actually bootstrap date pickers. They always come with some default values. Now, I want when user change those two values to calculate the difference between two dates (alert or console log will do, I will find my way from there).
Problem is that I have no clue where to start and how to do that calculation. Again I guess that onchange event may be a good candidate but...I have no idea how to calculate the difference.
Any help will be deeply appreciated.
Regards, John
You could first parse your string an create a JavaScript date like that:
var start = $("input[name=checkin]").val().split("/");
var end = $("input[name=checkout]").val().split("/");
var startDate = new Date(start[2], start[1]-1, start[0]);
var endDate = new Date(end[2], end[1]-1, end[0]);
Then you can simply substract the dates from each other:
endDate - startDate
That substraction will give you the time difference in milliseconds. To convert that to days, simply divide it by the number of milliseconds in a day (1000 * 60 * 60 * 24).
Now you have the difference in days. For an example, see JSFiddle.
<script type="text/javascript">
//Set the two dates
today=new Date()
var christmas=new Date(today.getFullYear(), 11, 25) //Month is 0-11 in JavaScript
if (today.getMonth()==11 && today.getDate()>25) //if Christmas has passed already
christmas.setFullYear(christmas.getFullYear()+1) //calculate next year's Christmas
//Set 1 day in milliseconds
var one_day=1000*60*60*24
//Calculate difference btw the two dates, and convert to days
document.write(Math.ceil((christmas.getTime()-today.getTime())/(one_day))+
" days left until Christmas!")
This short Javascript will display the DAY difference between today (value 1) and christmas (your value 2). Ovbioulsy these can be replaced with our two values and should then work.
Example: 146 days left until Christmas!
var date1 = new Date("7/11/2010");
var date2 = new Date("12/12/2010");
var timeDiff = Math.abs(date2.getTime() - date1.getTime());
var diffDays = Math.ceil(timeDiff / (1000 * 3600 * 24));
alert(diffDays)​;
Try this . i found it from this link

the closest Sunday before given date with JavaScript

I need to know the date for last Sunday for given date in php & javascript
Let's have a function give_me_last_Sunday
give_me_last_Sunday('20110517') is 20110515
give_me_last_Sunday('20110604') is 20110529
The full backup is done on Sundays = weekly. If I want to restore daily backup I need full (weekly) and daily backup. I need to copy backup files before restoring to temp directory so I restoring daily backup I need to know what weekly backup file I need to copy along the daily file.
My thought was to get Julian representation (or something similar) for the given date and then subtract 1 and check if it is Sunday ... Not sure if this is the best idea and how to convert given date into something I can subtract.
Based on Thomas' effort, and provided the input string is exactly the format you specified, then:
function lastSunday(d) {
var d = d.replace(/(^\d{4})(\d{2})(\d{2}$)/,'$1/$2/$3');
d = new Date(d);
d.setDate(d.getDate() - d.getDay());
return d;
}
Edit
If I were to write that now, I'd not depend on the Date object parsing the string but do it myself:
function lastSunday(s) {
var d = new Date(s.substring(0,4), s.substring(4,6) - 1, s.substring(6));
d.setDate(d.getDate() - d.getDay());
return d;
}
While the format yyyy/mm/dd is parsed correctly by all browsers I've tested, I think it's more robust to stick to basic methods. Particularly when they are likely more efficient.
Ok so this is for JavaScript only. You have an input that you need to extract the month, date, and year from. The following is just partly an answer then on how to get the date:
<script type="text/javascript">
var myDate=new Date();
myDate.setFullYear(2011,4,16)
var a = myDate.getDate();
var t = myDate.getDay();
var r = a - t;
document.write("The date last Sunday was " + r);
</script>
So the setFullYear function sets the myDate to the date specified where the first four digits is the year, the next are is the month (0= Jan, 1= Feb.,...). The last one is the actually date. Then the above code gives you the date of the Sunday before that. I am guessing that you can add more code to get the month (use getMonth() method). Here are a few links that might be helpful
http://www.w3schools.com/js/js_obj_date.asp
http://www.w3schools.com/jsref/jsref_setFullYear.asp
http://www.w3schools.com/jsref/jsref_getMonth.asp
(You can probably find the other functions that you need)
I hope this helps a bit even though it is not a complete answer.
Yup and strtotime has been ported to JS for eg http://phpjs.org/functions/strtotime:554 here.
final code (big thanks to #Thomas & #Rob)
function lastSunday(d) {
var d = d.replace(/(^\d{4})(\d{2})(\d{2}$)/,'$1/$2/$3');
d = new Date(d);
d.setDate(d.getDate() - d.getDay());
year = d.getFullYear()+'';
month = d.getMonth()+1+'';
day = d.getDate()+'';
if ( month.length == 1 ) month = "0" + month; // Add leading zeros to month and date if required
if ( day.length == 1 ) day = "0" + day;
return year+month+day;
}

Categories

Resources