Javascript: Calculating time duration on ajax response - javascript

I am trying to calculate the time duration of a tasks, that I get from an ajax response.
Following are my table values:
Jobid techid, techtype, notes, starttime, stoptime
1 1 Brakes Break disc needed to be changed 2020-07-16 13:00:00 2020-07-16 13:40:00
1 2 Oil Change Replaced oil 2020-07-17 08:00:00 2020-07-17 09:00:00
1 3 Cleaning Cleaned the vehicle 2020-07-17 10:00:00 2020-07-17 10:30:00
On my ajax response, in the above case, I am getting 3 objects each having the start time, and stop time. I want to calculate total time spent in hours and minutes.
Is there an easy way to calculate the total duration?

With a string like 2020-07-16 13:00:00 you can construct a JS Date and get the milliseconds since the UNIX epoch with getTime() like so
new Date('2020-07-16 13:00:00').getTime()
Or, if you prefer, as pointed out by #Yousaf in the comments you can actually just use the - operator with Dates directly and get the millisecond difference
// resolves to 3600000, or 1 hour in milliseconds
new Date('2020-07-16 13:00:00') - new Date('2020-07-16 12:00:00')
Using that, you can get the difference in milliseconds between any two dates, and convert that to hours / minutes / whatever with straightforward arithmetic.

You can simply use Date to construct a date and then minus the start time from the end time.
Here I use getTime to get the millisecond difference, divide by 1000 to get seconds and divide by 60 to get minutes.
You could also use getMonth and such if you have bigger differences.
const starttime = '2020-07-16 13:00:00'
const stoptime = '2020-07-16 13:40:00'
const duration = new Date(stoptime) - new Date(starttime)
console.log(duration / 1000 / 60)

[UPDATE]
I think you can check this answer, but basically you should convert each date to js Date, get the milliseconds and just calculate endtime - startime.
const timelapse = new Date(endtime).getTime() - new Date(startime).getTime();
From there, you transform that in the unit you need (e.g: seconds = milliseconds/1000);
Sorry, my bad for writing fast.

Related

How does moment.js handle leap seconds?

I need a way to always add a whole minute to a timestamp, even if the minute is 61 seconds long due to a planned leap second. Does anyone know if moment().add(1, 'minute') adds a minute regardless of leap seconds? Or does it just always add sixty seconds?
I've found how it handles addition over daylight savings time and leap years, but nothing at all for leap seconds.
To give some background as to why this is important:
I need to create a CSV file with a bunch of minute-by-minute sensor data for various sensors, formatted like:
time,sensor1,sensor2
1491329921800,20,21
1491329981800,22,21
My data is stored with with the timestamp for the start of an hour, then an array of sixty data points for the hour.
{
timestamp: Date(2017,2,24,12,0,0),
temperature: [20, 22, 23, ... <60 elements total>]
}
I turn this into a bunch of timestamp'd data by giving the first data point the hour's timestamp and adding sixty seconds to that value for each subsequent data point (as leap seconds always happen at the end of the hour and I only ever do an hour at a time, this should be fine).
I then will need to build a dictionary mapping each timestamp to the value at that minute. This is necessary so that I can have the right data in the right row of the CSV; sensors may have started at different times or may have been powered off for a certain hour or not reported for a certain part of the hour; I can't just assume that all sensors have the same data.
I'm finding all of the timestamps over which the CSV will be created with the following code:
var date = moment(startDate);
var end = endDate.getTime();
var timestamps = [];
while(date.valueOf() < end) {
timestamps.push(date.valueOf());
date.add(1, 'minute')
}
timestamps.push(date.valueOf());
But I'm not sure if it's safe. If I need to, I could just change date.add(1, 'minute') to date.add(1, 'minute').startOf('minute'), but this could add a lot to the execution time and I'd like to avoid it if possible.
You don't need to worry about this, because JavaScript is unaware of leap-seconds. Consider this piece of code :-
// 1. Initialize date
var newDate = new Date('1 March 1972 11:30:00');
// 2. Convert to milliseconds and add 20 years
var msec = Date.parse(newDate) + 631152000000;
// 3. Convert milliseconds back to normal date format
newDate = new Date(msec);
The big number in step #2 is the number of milliseconds in 20 years, as given by the equation ((15 x 365) + (5 x 366)) x 24 x 60 x 60 x 1000; 15 years # 365 days per year plus 5 years # 366 days per year, 24 hours per day, 60 minutes per hour, 60 seconds per minute, 1000 milliseconds per second.
After execution the answer given is '1 March 1992 11:30:00'. If JavaScript took account of leap-seconds it would be '1 March 1992 11:30:16', because 16 extra seconds had happened (or '1 March 1992 11:29:44' depending how you look at it).
Summarily, if you need to know how many milliseconds have actually passed between two dates, then you need to write some code to do a lookup of how many leap-seconds occurred within the period they span (you can find the raw data for that here), but for normal time logging we can happily ignore this unwelcome little complication.

Moment.JS - Change a two digit value to milliseconds using moment

At the moment I have an input field that allows you to choose an hour by entering two digits. for example you could choose 12 for 12 hours.
Is there a way using moment to convert that number into milliseconds using MomentJS?
At the moment I am having to do the below maths. I can't see in the Moment docs that this is doable.
var timeHH = scope.session.timeHH * 3600;
This works out the seconds, then later I mulitply it by 1000 for the milliseconds value.
Is there a way using moment to convert that number into mini milliseconds using moment?
There may be, but there's absolutely no reason to use MomentJS for this, and doing so would be roundabout and inefficient. It's quite straightforward: hours * 3600000 is milliseconds. There are no weird special cases to handle, etc., unless you're handling converting a particular period of hours of a real time (say, the 10 hours from 8 p.m. December 31st 2005 GMT) and want to handle leap second insertions (there was one that night at midnight), but MomentJS doesn't do that anyway.
For this particular use case, the right thing to do is a manual calculation. For the sake of completeness and in the event you needed to do more complicated calculations, to do this with Moment, you would use the duration type. The duration type will allow you to convert from one unit value to another, and if you had to make several unit conversions instead of just this one it would be a good choice.
moment.duration(12, 'hours').asMilliseconds()
43200000
In addition to converting to milliseconds, you could convert to any other unit:
var dur = moment.duration(12, 'hours');
dur.asMilliseconds();
43200000
dur.asDays();
0.5
dur.asYears();
0.001368953503494254
In addition to the as functions, you can get the parts of the duration broken out:
var dur = moment.duration(12.5, 'hours');
dur.hours();
12
dur.minutes();
30
dur.seconds();
0
Or call humanize to get a human readable string that is an estimate of the duration's length:
var dur = moment.duration(42, 'hours');
dur.humanize();
"2 days"
You can also do math with durations. See the docs for more info: http://momentjs.com/docs/#/durations/
You can try the following hack(assuming hours in 24-Hours format) :
var momObj = moment('12', 'HH');
var x = momObj.diff(moment().startOf('day'));
console.log(x) //43200000

Convert exact date to time ago using jquery - What format for the date?

I have a static page which will specify a hardcoded exact date. If the use has javascript, I want to then convert this hardcoded exact date into a "time ago".
For example:
3 hours ago
My question is, in what format of date will javascript be able to most efficiently convert to the time ago?
10/10/13
10.10.13
10th October 2013
101013
I would look at this post: https://stackoverflow.com/a/3177838/2895307
In it he just uses a javascript Date() as the parameter to the "timeSince()" function. To create a javascript Date from your hardcoded string you can use this format:
var d1 = new Date("October 13, 1975 11:13:00")
definitely unix timestamp is the best format for all date and time calculations, you can convert the results to a more readable format later.
the calculation is simple, you start with the timestamp of an event in the past, for example:
var anHourAgo = Date.now() - 3600000;
then you substract that from the current timestamp and get the number of milliseconds that have passed since that event
Date.now() - anHourAgo
then you can pass that to any function that will convert those milliseconds to hours, minutes and seconds, here's an example that takes seconds and returns an array with that info, and another function that pads those numbers with zeros
var zeroPad = function(n){
return n.toString().replace(/^(\d)$/,'0$1');
};
var formatSecs = function(s){
var r = [
Math.floor(s / 3600),
Math.floor(s%3600 / 60),
Math.floor((s%3600)%60)
];
r.push(zeroPad(r[0])+':'+zeroPad(r[1])+':'+zeroPad(r[2]));
return r;
};
the formatSecs function expects seconds instead of millseconds, you should divide by 1000 and round that number, then pass that number to the function
Math.round(Date.now() - anHourAgo) / 1000
Finally here's a working example of all that code in action:
http://codepen.io/DavidVValdez/pen/axHGj
i hope this helps, cheers!
The easiest thing to do would be to use Date.getTime().
This will give you the number of milliseconds since the Unix epoch and will make the math very simple.
Date.getTime

Number change every 24 hours

I would like to provide a list of about 40 positive numbers and then have my home page display the first number. Then at midnight, the number will change to the next number in the list. When at the end of the list, the rotation starts over. So for instance, a user goes to my page several times today and sees the first number in the list. Then say 1:00am, they go back to the page and see the next number on the list and will do so until midnight tomorrow night...etc etc etc Is this possible?
I've tried several different javascripts that does change the number according to my list BUT when a user goes to the page, it starts the list over again.
I am so new to this, I don't know which part of my code you might need since what I have been trying does what its supposed to do...just not how I want it to do.
Do I make sense?
Unfortunately, I won't be able to use php for this webpage.
You can use new Date().getTime() to get the current time in milliseconds. If you convert that to days, and round down, you can find the number of days since the epoch. Take the modulo of that and use it to obtain the index of your array of numbers. Since you're always using the current time (according to the user), you don't need to store any cookies or server-side counter.
var nums = [1,1,2,3,5,8,13]; // and so on
d = new Date(), // today
days = d.getTime() / (1000*60*60*24),
idx = Math.floor(days) % nums.length;
alert(nums[idx]); // should change once a day
Define a start date (preferably in the past), calculate today's date, subtract the two, and then use modulo to squeeze it into the range of numbers you want to show:
var minDate = 15681, // days since 1-1-1970
nowDate = Math.ceil(new Date().getTime() / 1000 / 86400),
numbers = [1, 5, 1234, 6543, 1236456];
// get the number for today
console.log(numbers[(nowDate - minDate) % numbers.length]);
If the start date doesn't matter, you can simplify the expression to:
numbers[Math.ceil(new Date().getTime() / 86400000) % numbers.length];
Btw, this won't change at midnight for everyone btw, because .getTime() gives GMT time.

How to determine if it is day or night in Javascript? [duplicate]

This question already has answers here:
Calculating sunrise/sunset times in Javascript
(4 answers)
Closed 1 year ago.
Im wanting to apply different CSS sheets to my site depending on the time of the browser. e.g if its day time, display day.css or night.css for night.
I can do this with PHP but it is based on the server time, not the browsers local time.
Is there a way to tell the time in javascript? I'm probably going to use jQuery to simply initiate the css once its worked out.
var hr = (new Date()).getHours(); //get hours of the day in 24Hr format (0-23)
Depending on your definition of day/night, perform your magic :)
PS: If your day/night starts not at the exact hour, you can try getMinutes().
I use this logic:
const hours = new Date().getHours()
const isDayTime = hours > 6 && hours < 20
(new Date).getHours()
will get the local hour of the time (0-23) of the client. Based on that value, swap the stylesheet for the page. I would set the day stylesheet as the default and swap it out when necessary.
My initial thought is that you would want to perform this operation as soon as possible on the client to avoid any potential browser reflow.
For this to work you’ll need to know the location of the client, the local sunrise and sunset time and the day of the year. Only locations at the equator have an almost constant 12 hour of day light all the year around.
This other answer on StackOverflow provides a good answer:
Calculating sunrise/sunset times in Javascript
Fun question. I wanted to give it a try and come up with something totally different than what was proposed so far. This is what I got:
function isDay() {
return (Date.now() + 60000 * new Date().getTimezoneOffset() + 21600000) % 86400000 / 3600000 > 12;
}
It will return true if it's between 6 AM and 6 PM, or false otherwise.
Breaking down into parts:
Date.now() returns UTC epoch in milliseconds;
new Date().getTimezoneOffset() gets local time zone, in minutes, and 60000 just converts it to milliseconds;
21600000 represents 6 hours in milliseconds. This is a hack to pretend each day starts at 6 AM (will be explained in the end);
86400000 is how many milliseconds there is in a day, so X % 86400000 will return how many milliseconds have passed since the current day begun; since we added 6 hours in the previous step, this is actually counting millis since 6 AM;
we divide that result by 3600000 (number of milliseconds in an hour) to find out how many hours have passed since the day begun;
since we added 6 hours to our clock, 6 AM is now 12 PM, and 6 PM is actually midnight. This is why the function checks to see if the value is greater than 12; if it is, it must be between 6 AM and 6 PM right now. Anything earlier than 6 AM or later than 6 PM becomes less than 12, according to that formula.
Of course, the same can be accomplished with:
function isDay() {
const hours = (new Date()).getHours();
return (hours >= 6 && hours < 18);
}
But that is not even half as fun :-D

Categories