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>
Related
I want to subtract lunch hours from datetime differece
How it can be achieved?
var StartTime = moment(theList[i].start_time, "YYYY-MM-DD HH:mm:ss"); //2020-04-01 08:00:00.0
var EndTime = moment(theList[i].end_time, "YYYY-MM-DD HH:mm:ss"); //2020-04-01 18:00:00.0
var Lunch = moment(theList[i].lunch_time, "HH:mm:ss"); //00:30:00
var lunchTimeMs= moment(Lunch,"HH:mm:ss");
var ms = moment(EndTime,"YYYY-MM-DD HH:mm:ss").diff(moment(StartTime,"YYYY-MM-DD HH:mm:ss"));
var d = moment.duration(ms);
ms = moment().subtract(lunchTimeMs); //This gives wrong result
var s = Math.floor(d.asHours()) + moment.utc(ms).format(":mm:ss");
console.log("Total time " + i + " row" + s);
He is using Moment JS.
As far as I understood, the problem is that he has only date with time to manipulate in format similar to: dd.mm.YYYY HH:ii:ss.
My recommendation was to transfer server response datetime to timestamp using JS. It's much easier to manipulate date and time differences if you are using a timestamp.
UPDATE
Adding here my "vision" of JS date management (my fiddle). Feel free to improve it!
const date2timestamp= function(str){
_tmp = str.split(" ");
if(_tmp){
date_arr = ( _tmp[1] ? _tmp[0].split("-") : null );
time_arr = ( _tmp[1] ? _tmp[1].split(":") : _tmp[0].split(":") );
if(!date_arr) {
const today = new Date();
_date = Date.UTC(today.getFullYear(), today.getMonth(), today.getDate(), time_arr[0], time_arr[1], time_arr[2]);
}
else {
_date = Date.UTC(date_arr[0], date_arr[1]-1, date_arr[2], time_arr[0], time_arr[1], time_arr[2]);
}
date_obj = new Date(_date);
return date_obj.getTime()/1000;
}
return false;
}
document.write(
date2timestamp("2020-04-20 08:00:00")+"<br/>",
date2timestamp("2020-04-20 17:00:00")+"<br/>",
date2timestamp("00:03:00")
);
And now you have timestamps. When you subtract, you know, that the 1min = 60sec, so the result is ((7*60)+30)*60 = date2timestamp("2020-04-20 17:00:00")-date2timestamp("2020-04-20 17:00:00")-(30*60)
MORE UPDATES
But, reading about the moment.js a bit, there is even easier way. Manual for subtract says:
moment().subtract(1, 'seconds');
that means, you have to actually transfer your Launch period into seconds and then add put it into the subtract: moment().subtract((30*60), 'seconds') or just add (for test) 'millisecond' as second part of subtract:
...
ms = moment().subtract(lunchTimeMs, 'milliseconds');
// or use that
ms = moment().subtract(lunchTimeMs/1000, 'seconds);
...
Try this:
var StartTime = moment(theList[i].start_time, "YYYY-MM-DD HH:mm:ss");
var EndTime = moment(theList[i].end_time, "YYYY-MM-DD HH:mm:ss");
var Lunch = moment(theList[i].lunch_time, "HH:mm:ss");
var ms = moment(EndTime,"YYYY-MM-DD HH:mm:ss").diff(moment(StartTime,"YYYY-MM-DD HH:mm:ss"));
moment(ms).subtract(Lunch);
I have two times (basically start time and end time). Also, I have the number of questions played by the user. I wanna know the average time user spent for each question.
//startGameTime: 2019-07-27T07:58:42.000Z
//endGameTime: 2019-07-27T07:59:57.000Z
function averageQuestionTime(startGameTime, endGameTime, totalNumberOfQuestions) {
var d1 = new Date(startGameTime);
var d2 = new Date(endGameTime);
var d1msecs = new Date(d1).getTime(); // get milliseconds
var d2msecs = new Date(d2).getTime(); // get milliseconds
var avgTime = (d1msecs + d2msecs) / totalNumberOfQuestions;
var date = new Date(avgTime);
var hour = date.getUTCHours();
var min = date.getUTCMinutes();
var sec = date.getUTCSeconds();
var day = date.getUTCDate() - 1;
return (day + ":" + hour + ":" + min + ":" + sec)
}
I understand my logic is completely flawed as the units for date and time and nos of questions are different. What is the best way to achieve the result ?
There are good libraries which prevent the users from having to reinvent the wheel every time they want to manipulate date/time in Node.
Obtaining time difference is pretty simple (I can see you are doing it correctly to obtain the difference in milliseconds) and libraries make them even simpler.
See how simple it is using momentJS
var moment = require('moment');
var startDate = moment('2019-7-24 00:00:00', 'YYYY-M-DD HH:mm:ss');
var endDate = moment('2019-7-24 05:27:31', 'YYYY-M-DD HH:mm:ss');
var diffSeconds = endDate.diff(startDate, 'seconds');
var diffHours endDate.diff(startDate, 'seconds');
console.log(`Avg in secs: ${diffSeconds / totalNumberOfQuestions}`);
console.log(`Avg in secs: ${diffHours/ totalNumberOfQuestions}`);
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');
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;
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;