Get difference between 2 dates in javascript - javascript

var date1 = new Date("04.11.2016");
var date2 = new Date("19.11.2016");
var timeDiff = Math.abs(date2.getTime() - date1.getTime());
var diffDays = Math.ceil(timeDiff / (1000 * 3600 * 24));
alert(diffDays);
Trying get different between those Dates, but my date format is that "04.11.2016", Result show NaN

var date1 = new Date("11/04/2016");
var date2 = new Date("11/19/2016");
var timeDiff = Math.abs(date2.getTime() - date1.getTime());
var diffDays = Math.ceil(timeDiff / (1000 * 3600 * 24));
alert(diffDays);
change the format of date.
it should be MM/DD/YYYY
Hope this helps.

The easiest way is to use moment.js library:
var date1 = moment('04.11.2016', 'MM.DD.YYYY'),
date2 = moment('19.11.2016', 'MM.DD.YYYY'),
diffDays = date2.diff(date1, 'days'); // you can wrap it in Math.abs()
The ugly js way:
var input1 = '04.11.2016',
parts1 = input1.split('.'),
date1 = new Date(parts1[2], parts1[1], parts1[0]),
input2 = '19.11.2016',
parts2 = input2.split('.'),
date2 = new Date(parts2[2], parts2[1], parts2[0]),
timeDiff = Math.abs(date2.getTime() - date1.getTime()),
diffDays = Math.ceil(timeDiff / (1000 * 3600 * 24));

Change the Month and Date order First should be month then date... MM/DD/YYYY
var date1 = new Date("11.04.2016");
var date2 = new Date("11.19.2016");
var timeDiff = Math.abs(date2.getTime() - date1.getTime());
var diffDays = Math.ceil(timeDiff / (1000 * 3600 * 24));
alert(diffDays);

Your second date is incorrect. Parser is considering this format MM.DD.YYY and you have supplied out of range month.
var date1 = new Date("04.11.2016");
var date2 = new Date("09.11.2016");
var timeDiff = Math.abs(date2.getTime() - date1.getTime());
var diffDays = Math.ceil(timeDiff / (1000 * 3600 * 24));
alert(diffDays);

A date consists of a year, a month, a day, an hour, a minute, a second, and milliseconds.
Date objects are created with the new Date() constructor.
There are 4 ways of initiating a date:
new Date()
new Date(milliseconds)
new Date(dateString)
new Date(year, month, day, hours, minutes, seconds, milliseconds)
so you can split them and then use it

Just change the first two lines as below
var date1 = new Date(2016,11,4);
var date2 = new Date(2016,11,19);

new date("mm dd yyyy") format was wrong
(function () {
var date1 = new Date("11 04 2016");
var date2 = new Date("11 19 2016");
var timeDiff = Math.abs(date2.getTime() - date1.getTime());
var diffDays = Math.ceil(timeDiff / (1000 * 3600 * 24));
console.log(diffDays);
})()

JS expects date to in MM-DD-YYYY and not DD-MM-YYYY. Ideal way would be to use moment.js, but you can use something like this:
function createCustomDate(dateString){
var dateArr = dateString.split(/[^0-9]/).reverse().join("-")
return new Date(dateArr);
}
var dateStr1 = "04.11.2016";
var dateStr2 = "19.11.2016";
var date1 = createCustomDate(dateStr1);
var date2 = createCustomDate(dateStr2);
var timeDiff = Math.abs(date2.getTime() - date1.getTime());
var diffDays = Math.ceil(timeDiff / (1000 * 3600 * 24));
console.log(diffDays);

new Date("19.11.2016");
this is Invalid Date. So, difference is be NaN .
change the format to mm/dd/yyyy and it will work.

You can use moment.js,
d = moment('11.16.2016') // here date format was in "MM.DD.YYYY"
e = moment('11.04.2016') // here date format was in "MM.DD.YYYY"
getDiffbydays = e.diff(d,'days') // get diff by days you can use day
getDiffbyyears = e.diff(d,'year') // get diff by years you can use year
getDiffbymonth = e.diff(d,'month') // get diff by months you can use month

Check this solution which uses a function called getDate to convert the date string of the format "04.11.2016" to a JavaScript Date object.
function getDate(dateStr) {
var arr = dateStr.split('.');
return new Date(arr[2], arr[1], arr[0]);
}
var start = getDate("04.11.2016");
var end = getDate("19.11.2016");
var timeDiff = Math.abs(end.getTime() - start.getTime());
var diffDays = Math.ceil(timeDiff / (1000 * 60 * 60 * 24))
console.log('Number of days: ' + diffDays);
In order to use this code to create a Custom JavaScript Variable in Google Tag Manager, you can modify the above code or the one which you choose to be inside a function - reference.

Related

How I will get difference between two Month(YYYYMM) in JavaScript?

var frommonth="201912";
var tomonth="201810";
From Above Two Month how i will get difference between two Month in JavaScript?
var date1 = new Date(fromdate);
var date2 = new Date(todate);
var timeDiff = Math.abs(date2.getTime() - date1.getTime());
var diffDays = Math.ceil(timeDiff / (1000 * 3600 * 24));
var fromYear=date1.getFullYear();
var toYear=date2.getFullYear();
var diffyear =toYear-fromYear;
new Date() dont parse YYYYMM. It consider 201912 as year
So Use match() to parse YYYYMM
var from = "201912";
var to = "201810";
function parseMonth(str) {
return str.match(/(\d{4})(\d{2})/).splice(1).map(Number)
}
var [fromY, fromM] = parseMonth(from)
var [toY, toM] = parseMonth(to)
var result = (fromY - toY) * 12 + (fromM - toM)
console.log(result, 'months')
You can pass the frommonth and tomonth to the function as parameters and can perform calculation of difference..
Here new Date(frommonth.substring(0,4), frommonth.substring(4), 0) denotes,
-> frommonth.substring(0,4) => Getting the year from the string
-> frommonth.substring(4) => Getting the month from the string
-> 0 => Setting up date as 0.
And the same has been considered for tomonth as well..
Also Math.round(timeDiff / (2e3 * 3600 * 365.25)); is made to consider the leap year as well..
const frommonth = "201912";
const tomonth = "201810";
const diffInMonths = (end, start) => {
var timeDiff = Math.abs(end.getTime() - start.getTime());
return Math.round(timeDiff / (2e3 * 3600 * 365.25));
}
const result = diffInMonths(new Date(frommonth.substring(0,4), frommonth.substring(4), 0), new Date(tomonth.substring(0,4), tomonth.substring(4), 0));
//Diff in months
console.log(result);

Calculate difference of months and semi-month difference between two dates using Jquery

I want correct results even if month has 31 days or 30 days.
var startDt = $("input[id=StartDate_" + i + "]").val();
var endDt = $("input[id=EndDate_" + i + "]").val();
var diff = new Date(Date.parse(endDt) - Date.parse(startDt));
var days = ((diff / 1000 / 60 / 60 / 24) + 1);
if (SelVal == "Monthly") {
$("#div" + i).html(Math.ceil(days / 30));
}
if (SelVal == "Semi-monthly") {
$("#div" + i).html(Math.ceil(days / 15));
}
I want to calculate difference where is Start Date is 10 April 2019 and End Date is 14 May 2019. I want monthly and semi-monthly. For this example:
Number of months difference would be 1
Semi-monthly difference would be 3 as mid of the month is
counted by date 15 of every month.
For example the billing of any center takes place every 1st and 15th date of the month and I need number of billings between two dates.
Okay try this:
var date1 = new Date("10/31/2019");
var date2 = new Date("12/1/2019");
var timeDiff = Math.abs(date2.getTime() - date1.getTime());
var diffDays = Math.ceil(timeDiff / (1000 * 3600 * 24));
console.log(diffDays)
console.log("months: "+ (Math.floor(diffDays/30)));
console.log("days: "+ (diffDays%30));
have a look to the code snippet
var date1 = new Date("10/31/2019");
var date2 = new Date("12/1/2019");
var timeDiff = Math.abs(date2.getTime() - date1.getTime());
var diffDays = Math.ceil(timeDiff / (1000 * 3600 * 24));
console.log(diffDays)
console.log("months: "+ (Math.floor(diffDays/30)));
console.log("days: "+ (diffDays%30));

Check if date is within X number of days of today

I have a date variable being set on my page like this:
startDate = "03/28/2017";
How can I check if that date is 7 or less days before today's date?
It will need to be used in a conditional if statement.
You can try using moment.js,
var a = moment([2007, 0, 29]);
var b = moment([2007, 0, 28]);
a.diff(b) // 86400000
or even better, it has an inbuilt method, which says after how many days.
moment([2007, 0, 29]).toNow(); // in 4 years
and if you want to use old plain javascript :
var date1 = new Date("3/30/2017");
var date2 = new Date("3/23/2017");
var timeDiff = Math.abs(date2.getTime() - date1.getTime());
var diffDays = Math.ceil(timeDiff / (1000 * 3600 * 24));
If you want to compare with today
var date1 = new Date("3/23/2017")
var date2 = new Date();

.Click function trigger just one time in java script

I read many questions here but not find a solution for problem.
I have one page which has two dates and one text box. When I click on text box the difference of two dates in days will show on text box. But when I change the dates and click on text box it doesn't work.
Code
$('#totalNoOfLeave').click(function(){
var date1 = new Date($('#leaveStartDate').getValue());
var date2 = new Date($('#leaveEndingDate').getValue());
var timeDiff = Math.abs(date2.getTime() - date1.getTime());
var diffDays = Math.ceil(timeDiff / (1000 * 3600 * 24));
$('#totalNoOfLeave').setValue(diffDays);
});
Please help.
Use this :
$('body').on('click', '#totalNoOfLeave', function () {
var date1 = new Date($('#leaveStartDate').getValue());
var date2 = new Date($('#leaveEndingDate').getValue());
var timeDiff = Math.abs(date2.getTime() - date1.getTime());
var diffDays = Math.ceil(timeDiff / (1000 * 3600 * 24));
$('#totalNoOfLeave').setValue(diffDays);
});

How do you get the unix timestamp for the start of today in javascript?

I realize that the current timestamp can be generated with the following...
var timestamp = Math.round((new Date()).getTime() / 1000);
What I'd like is the timestamp at the beginning of the current day. For example the current timestamp is roughly 1314297250, what I'd like to be able to generate is 1314230400 which is the beginning of today August 25th 2011.
Thanks for your help.
var now = new Date();
var startOfDay = new Date(now.getFullYear(), now.getMonth(), now.getDate());
var timestamp = startOfDay / 1000;
Well, the cleanest and fastest way to do this is with:
long timestamp = 1314297250;
long beginOfDay = timestamp - (timestamp % 86400);
where 86400 is the number of seconds in one day
var now = new Date; // now
now.setHours(0); // set hours to 0
now.setMinutes(0); // set minutes to 0
now.setSeconds(0); // set seconds to 0
var startOfDay = Math.floor(now / 1000); // divide by 1000, truncate milliseconds
var d = new Date();
d.setHours(0);
d.setMinutes(0);
d.setSeconds(0);
d.setMilliseconds(0);
var t = d / 1000;
Alternatively you could subtract the modulo of a days length in miliseconds e.g.
var day = 24*60*60*1000;
var start_of_today = Date.now() - Date.now() % day;
Luis Fontes' solution returns UTC time so it can be 1 hour (daylight saving time) different from setHours solution.
var d = new Date();
var t = d - (d % 86400000);
Simplified version of examples above (local time).
var d = new Date();
d.setHours(0,0,0,0);
var t = d / 1000;
Here you can find some performance tests: http://jsperf.com/calc-start-of-day
Another alternative for getting the beginning of the day is the following:
var now = new Date();
var beginningOfDay = new Date(now.getTime() -
now.getHours() * 60 * 60 * 1000 -
now.getMinutes() * 60 * 1000 -
now.getSeconds() * 1000 -
now.getMilliseconds());
var yoursystemday = new Date(new Date().getTime()-(120000*60+new Date().getTimezoneOffset()*60000));
yoursystemday = new Date();
var current_time_stamp = Math.round(yoursystemday.getTime()/1000);
For any date it's easy to get Timestamps of start/end of the date using ISO String of the date ('yyyy-mm-dd'):
var dateString = '2017-07-13';
var startDateTS = new Date(`${dateString}T00:00:00.000Z`).valueOf();
var endDateTS = new Date(`${dateString}T23:59:59.999Z`).valueOf();
To get ISO String of today you would use (new Date()).toISOString().substring(0, 10)
So to get TS for today:
var dateString = (new Date()).toISOString().substring(0, 10);
var startDateTS = new Date(`${dateString}T00:00:00.000Z`).valueOf();
var endDateTS = new Date(`${dateString}T23:59:59.999Z`).valueOf();
var now = new Date();
var startOfDay = new Date(now.getFullYear(), now.getMonth(), now.getDate());
var timestamp = startOfDay.getTime() / 1000;

Categories