Problems with diff function of moment - javascript

I need to subtract two dates with the diff function of moment, the problem is that it does not recognize the diff function which sends me an error
var fechaActual = new Date();
debugger;
var Datos = traeIdEstado();
var FechaEstadoAnterior = Datos[0];
var idEstado = Datos[1];
var dateA = moment(fechaActual).format('YYYY-MM-DD');
var dateB = moment(FechaEstadoAnterior).format('YYYY-MM-DD');
var d = dateA.diff(dateB, 'days',true);
alert(d);

The diff method only works with numbers, because the computer can't really tell the difference between strings. For this reason, you need to diff first, THEN format the result. Formatting doesn't really help the diff work in your example.
This Stack question Get hours difference between two dates should help you get the result you're looking for. You might have to convert the dates into hours to be able to get the diff, which are values it can use to compare.

The solution to the problem was as follows
var dateA = moment(fechaActual).format('YYYY-MM-DD');
var dateB = moment(FechaEstadoAnterior).format('YYYY-MM-DD');
//var d = dateA.diff(dateB, 'days',true);
//alert(d);
var d = moment(dateA).diff(moment(dateB), 'day');

Related

How to find time difference in seconds using moment.js

How can I find time difference in seconds between two different timezones.
I want to use moment for this -
My start time is something like- 2022-09-04T07:29:39Z[UTC] and end time will be the current time in my frontend.
My code =
var now = new Date().getTime();
var then = "2022-03-04T07:29:39Z[UTC]";
var ms = moment(now,"DD/MM/YYYY HH:mm:ss").diff(moment(then,"DD/MM/YYYY HH:mm:ss")); //NAN
var d = moment.duration(ms);
var s = d.format("hh:mm:ss");
console.log("Time Difference =",s);
I need help in this, currently I am getting ms as NAN how can I correct it!
This type of calculation can easily be done with Vanilla JavaScript:
const now = new Date().getTime(),
then = new Date("2022-03-04T07:29:39Z"),
tsec= Math.round((now-then)/1000),
sec=tsec%60, tmin=(tsec-sec)/60,
min=tmin%60, th=(tmin-min)/60,
h=th%24, d=(th-h)/24;
console.log(`Time Difference = ${d}d ${h}h ${min}m ${sec}s`);
d.format is not a function exposed by momentjs instead of that you should write like below
var now = new Date().getTime();
var then = "2022-03-04T07:29:39Z[UTC]";
var ms = moment(now,"DD/MM/YYYY HH:mm:ss").diff(moment(then,"DD/MM/YYYY HH:mm:ss"));
var d = moment.duration(ms);
var s = moment(d).format('hh:mm:ss')
console.log("Time Difference =",s);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>

Array of days in between months

I have two dates: Startdate and enddate
startdate = "10/10/2018" enddate = "03/09/2019"
I am trying to create an array of dates between those 2 dates. I have the following code.
function getDateArray (start, end) {
var arr = [];
var startDate = new Date(start);
var endDate = new Date(end);
endDate.setMonth( endDate.getMonth());
while (startDate <= endDate) {
arr.push(new Date(startDate));
startDate.setMonth(startDate.getMonth() + 1);
}
return arr;
}
Then calculate the number of days between those months in between.
10/10/2018 to 11/10/2018 = 30 days
11/10/2019 to 12/10/2018 = 30 days or so depending on number of days between the 2 dates and then create an array of the dates.
[30,30,31....till end date]
function daysBetween(date1, date2 )
{
var timeDiff = Math.abs(date2.getTime() - date1.getTime());
var dayDifference = Math.ceil(timeDiff / (1000 * 3600 * 24));
return dayDifference;
}
I tried the following code and it's returning the array of number of dates however, it's not accurate. It keeps returning 32 days in October. The output it's giving right now is as follows. I am not sure what i am doing wrong here but it looks like it's only going till February and displaying the result.
Any help will be appreciated. Thank you.
Output: [32,30,31,31,28]
var dateArr = getDateArray(z, y);
console.log(dateArr);
var dayCounts = "";
for (var x = 0; x < dateArr.length-1; x++)
{
dayCounts += daysBetween(dateArr[x], dateArr[x+1]);
}
console.log("datearrlength" + dateArr.length);
console.log(dayCounts);
i think this will work for you,
Date.prototype.addDay= function(days) {
var date = new Date(this.valueOf());
date.setDate(date.getDate() + days);
return date;
}
function getDateBwStartandEnd(sdate, edate) {
var dateArray = new Array();
var currentDate = sdate;
while (currentDate <= edate) {
dateArray.push(new Date (currentDate));
currentDate = currentDate.addDay(1);
}
return dateArray;
}
** Shamelessly copied from web, but this works fine for me.
While the following doesn't answer your question it is an alternative approach to the overall problem you are attempting to solve.
One approach would be to simply get the time difference between the two dates and then divide by the number of microseconds in a day. As you will notice though it is not exact and so a floor is used to get the days. There are other concerns with this approach as well such as date ranges before the epoch but it is a very simplistic approach and might work depending on your needs.
const startDate = '10/10/2018';
const endDate = '03/09/2019';
const start = (new Date(startDate)).valueOf();
const end = (new Date(endDate)).valueOf();
const timeBetween = end - start;
console.log({timeBetween, days: Math.floor(timeBetween/86400000)});
A slightly more robust is to essentially use a counter that increments itself by adding 1 day to the counter and the start date while the start date is less than the end date. Again, there are some concerns with this approach but that also depends on your needs.
const startDate = '10/10/2018';
const endDate = '03/09/2019';
let start = new Date(startDate);
const end = (new Date(endDate)).valueOf();
let daysBetween = 0;
while (start.valueOf() < end) {
daysBetween++;
start.setDate(start.getDate() + 1);
}
console.log(daysBetween);
Finally, a more robust solution to avoid the variety of issues with manipulating and working with dates is to use a library like momentjs. Using its difference method would look like the following.
const start = moment([2018, 10, 10]);
const end = moment([2019, 3, 9]);
console.log(end.diff(start, 'days'));
<script src="http://momentjs.com/downloads/moment.min.js"></script>
Using the following code worked for me. I added 1 extra month to my end date and it gives the proper date range. Also, instead of Math.ceil, i used Math.round and it gives the right number of date.
function getDateArray (start, end) {
var arr = [];
var startDate = new Date(start);
var endDate = new Date(end);
endDate.setMonth( endDate.getMonth());
while (startDate <= endDate) {
arr.push(new Date(startDate));
startDate.setMonth(startDate.getMonth() + 1);
}
return arr;
}

MomentJs subtract time to actual

I need to subtract actual time from a time variable (formatted in hh:mm:ss) and obtain the result in seconds, for example:
var time1 = "13:40:00";
var time1 = moment(time1, "HH:mm:ss");
var timeNow = ?
var time2 = time1 - timeNow // expressed in s
How can I achieve this?
I am not sure if I understood your needs fully but give this a try
var time1 = "13:40:00";
var time1 = moment(time1, "hh:mm:ss");
var time2 = time1.diff(moment(), 'seconds')
You can use moment diff to get the difference between two moment objects. In your case:
var time1 = '13:40:00';
var diff = moment().diff(moment(time1, 'HH:mm:ss'), 'seconds');
console.log(diff);
<script src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.13.0/moment.min.js"></script>
Try this:
var time1 = moment.duration("24:40:00", "HH:mm:ss").asSeconds();
var timeNow =moment.duration(moment().format('HH:mm:ss'),"HH:mm:ss").asSeconds();
var log = time1-timeNow;

Time from X not working as expected moment.js

$.each(data[i].replies, function(m, n) {
var currentdate = new Date();
console.log(n.entry.date_entered);
check = moment(n.entry.date_entered, 'YYYY/MM/DD');
check1 = moment(currentdate, 'YYYY/MM/DD');
console.log(check);
console.log(check1);
var month = check.format('M');
var day = check.format('DD');
var year = check.format('YYYY');
var month1 = check1.format('M');
var day1 = check1.format('DD');
var year1 = check1.format('YYYY');
get = moment([year, month, day]);
get1 = moment([year1, month1, day1]);
g = get1.from(get);
});
Sample n.entry.date_entered : 2014-07-28 12:23:43
For all the dates i am getting a few seconds ago don't know why
I think your problem is the format mask that you pass in to moment.
In your sample you use - as the delimiter but in your format mask you use /. This way moment will not be able to parse the date and will give you the current date instead.
Try changing your format mask to "YYYY-MM-DD".

calculate difference between two timestamp and get difference in unix timestamp

I want to calculate the difference between two dateTime, one date is submitted by user and other is current time:
user submitted time - now = difference in unix
user submitted time format is:
2014-03-26 10:52:00
Thanks for your help.
You can simply do this with getTime() which returns the number of milliseconds.
var ds = "2014-03-26 10:52:00";
var newDate = new Date(ds).getTime(); //convert string date to Date object
var currentDate = new Date().getTime();
var diff = currentDate-newDate;
console.log(diff);
Sometimes there are chance for cross browser compatibility in parsing the date string so it is better to parse it like
var ds = "2014-03-26 10:52:00";
var dateArray = ds.split(" "); // split the date and time
var ds1 = dateArray[0].split("-"); // split each parts in date
var ds2 = dateArray[1].split(":"); // split each parts in time
var newDate = new Date(ds1[0], (+ds1[1] - 1), ds1[2], ds2[0], ds2[1], ds2[2]).getTime(); //parse it
var currentDate = new Date().getTime();
var diff = currentDate - newDate;
console.log(diff); //timestamp difference
You can use MomentJS library
var user_submited_time = moment('2014-03-26 10:52:00');
var now = moment();
var value = user_submited_time - now;

Categories