Difference between two timestamps in hours minutes and seconds - javascript

I am trying to calculate the difference between two timestamp
"2020-03-18T17:34:45.856Z", "2020-03-18T16:34:45.856Z"
the difference should be like this: 2 hours 20min 30sec
I have tried using
return moment.utc(moment(startDate, 'HH:mm:ss').diff(moment(endDate, 'HH:mm:ss'))).format('HH:mm:ss');
m not sure how to get the desired format

You need to get it manually using Moment Duration
const startDate = "2020-03-18T17:34:45.856Z";
const endDate = "2020-03-18T16:34:45.856Z";
const diff = moment(startDate).diff(moment(endDate));
const duration = moment.duration(diff);
const hrs = duration.hours();
const mins = duration.minutes();
const secs = duration.seconds();
console.log(hrs + "hours " + mins + "min " + secs + "sec");
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>

Related

Elapsed ms to day?

I'm converting elapsed ms to HH:mm:ss, but if the elapsed ms are higher of a day, I lost that info:
const elapsedSeconds = 218509
const elapsed = moment.utc(elapsedSeconds * 1000).format('HH:mm:ss');
alert(elapsed); // print 12:41:49
How can I also display days from ms, near the HH:mm:ss?
In this case there are 60hours, so it should print 2(days):12:41:49. Or 60:41:49 at least.
So based on your required ouput you can use moment library to convert date time to specified format.
For that your code looks like :
const elapsedMilliseconds = 218509000;
const duration = moment.duration(elapsedMilliseconds);
const elapsed = duration.days() + "(days):" + duration.hours() + ":" + duration.minutes() + ":" + duration.seconds();
alert(elapsed);
Result :
2(days):12:41:49
If you want to do by javascript to get total HH:mm:ss then :
function padTo2Digits(num) {
return num.toString().padStart(2, '0');
}
function convertMsToHM(milliseconds) {
let seconds = Math.floor(milliseconds / 1000);
let minutes = Math.floor(seconds / 60);
let hours = Math.floor(minutes / 60);
seconds = seconds % 60;
minutes = seconds >= 30 ? minutes + 1 : minutes;
minutes = minutes % 60;
return `${padTo2Digits(hours)}:${padTo2Digits(minutes)}:${padTo2Digits(seconds)}`;
}
console.log(convertMsToHM(218509000));
Result :
"60:42:49"

How to get right format in moment js

i need to convert input value: ":2" to 'HH:mm' format.
":2" it should be converted to "00:20". All this process should be done with moment.js
let timeString = ":2";
const time = document.getElementById('time');
time.innerHTML = moment(timeString).format('HH:mm');
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.js"></script>
<span id="time"></span>
I didn't put input, because my problem is to get or convert correct format.
As stated before, you will have to convert the input yourself before passing it to momentjs - the following could work for you, depending on what the result for other values should be. I assumed:
":3" -> "00:30",
":21" -> "00:21",
"2:2" -> "02:20"
let timeString = ":2";
const hours = timeString.split(":")[0] || "00";
let minutes = timeString.split(":")[1];
if (minutes.length === 1) {
minutes = minutes * 10;
}
const parsedTime = hours + ":" + minutes;
const time = document.getElementById('time');
time.innerHTML = moment(parsedTime, "HH:mm").format("HH:mm");

How to add hours to string formatted as HH:MM:SS in 24 hour format

I'm trying to add hours to time in the format of 24 hours say '23:59:59'. I need to add, for example, 2.5 hours so the time should roll to the next day and be shown as '02:30:00'.
What I have tried so far works until it reaches '23:59:59'. I need to show the next day time if it exceeds '23:59:59'. Here is what I have tried so far:
var time = $('#starttime').val().split(':');
var d = new Date();
d.setHours(+time[0]);
d.setMinutes(time[1]);
d.setSeconds(time[2]);
var time2 = $('#endtime').val().split(':');
var endtimeval = new Date();
endtimeval.setHours(+time2[0]);
endtimeval.setMinutes(time2[1]);
endtimeval.setSeconds(time2[2]);
var str = d.getHours() + parseInt($('#noofhours').val()) + ":" + time2[1] + ":" + time2[2];
$('#endtime').val(str);
Using a Date Object here is possibly unnecessary, modulo arithmetic should suffice.
const pad = n => {
const s = String(n);
return s.length > 1 ? s : '0' + s;
};
const addHours = (timeVal, numHours) => {
const [hr, min, sec] = timeVal.split(':').map(Number);
const [,lefty, righty] = String(numHours).match(/(\d+)(?:(\.\d+))?/).map(Number);
const hours = (hr + lefty) % 24;
const minutes = righty === undefined ?
min :
((righty * 60 | 0) + min) % 60;
return [hours, minutes, sec].map(pad).join(':');
};
addHours('23:59:59', 2.5) // "01:29:59"
Note that since there's no dates involved it will not accurately handle e.g. daylight savings time. Also note that minutes are in this example rounded down, you could repeat the logic for seconds if desired.
Note that your approach using Date objects will give different answers for the same inputs depending on when/where the logic runs, for the same reasons.
Make a custom date adder?
const add = (time, hours) => {
let [hh, mm, ss] = time.split(':');
const seconds = hours * 60 * 60;
ss = ss * 1 + seconds;
if (ss >= 60) {
mm = mm * 1 + ss / 60;
ss = (ss % 60).toPrecision(2).padStart(2, '0');
}
if (mm >= 60) {
hh = hh * 1 + mm / 60;
mm = (mm % 60).toPrecision(2).padStart(2, '0');
}
hh = (Math.floor(hh) % 24).toString().padStart(2, '0');
return hh + ':' + mm + ':' + ss;
}
console.log(add("23:59:59", 2.5));
you may apply DRY principle and refactor the code yourself. But it will get the job done according to your requirement.
The simple trick that I did is just converted the hours entered as float/int to a minute value by multiplying to 60 and created a date, with this just added the time I already have.
Here the solution with minimal steps:
var time = $('#endtime').val().split(':');
var d = new Date();
d.setHours(+time[0]);
d.setMinutes(time[1]);
d.setSeconds(time[2]);
var addeddate = new Date();
addeddate.setMinutes(parseFloat($('#noofhours').val()) * 60);
$('#endtime').val(("0" + (addeddate.getHours())).slice(-2) + ":" + ("0" + (addeddate.getMinutes())).slice(-2) + ":" + ("0" + (addeddate.getSeconds())).slice(-2)); //The answer that I needed in endtime id value.
You can use vanilla JavaScript Date methods fairly easily here. Most of the work is parsing the time string inputs and then concatenating the time string output. For example:
const start = '23:59:59';
const add = '2.5';
const [hh, mm, ss] = start.split(':').map(x => parseInt(x));
const d = new Date(new Date().setHours(hh, mm + (add * 60), ss));
const end = `${d.getHours()}:${d.getMinutes()}:${d.getSeconds()}`;
console.log(end);
// 2:29:59

Difference between two dates by using angularjs?

This is my code
var departureDateFormat = new Date("10/09/15T09:25:00");
var arrivalDateFormat = new Date("13/09/15T13:25:00");
$scope.formats = ['dd-MMMM-yyyy', 'yyyy/MM/dd', 'dd.MM.yyyy', 'shortDate'];
$scope.format = $scope.formats[2];
var duration = moment.duration(arrivalDateFormat - departureDateFormat); //for reference of moment.js
var minutes = (duration / (1000 * 60)) % 60; // calliculating number of minutes
var hours = ((moment.duration(arrivalDateFormat - departureDateFormat)).humanize()); // calliculating number of hours
var timeInHours = ((hours == "an hour") ? 1 : hours.toString().substring(0, 1));
item.stopsDurationTime = timeInHours + "hrs " + minutes + "ms";
return timeInHours + "hrs " + minutes + "ms";
In the above code worked on IE , but it was not working on other browsers.Now i want to get difference between the above two dates by using angularJs/javascript.
You should use:
var minutes = duration.minutes();
var hours = duration.hours();
return hours + "hrs " + minutes + "ms";
Humanizing and then extracting the individual values is just unneeded overhead.
And moment can extract the hours and minutes for you so no need to compute from milliseconds.
Update:
Something like this:
var departureDate = moment("10/09/15T09:25:00", "DD/MM/YYYYTHH:mm:ss");
var arrivalDate = moment("13/09/15T13:35:10", "DD/MM/YYYYTHH:mm:ss");
var duration = moment.duration(arrivalDate.diff(departureDate));
var hours = Math.floor(duration.asHours());
var minutes = Math.floor(duration.asMinutes()-(hours*60));
return hours + "hrs " + minutes + "ms";
You have to define the format explicitly otherwise depending on your regional setting it will understand "10/09" as October, 9th or September, 10th.
Then you create a duration object. And you convert it to a number of hours (using "floor" to get a whole number). Then you convert it again to a number of minutes and subtract the hours you already got.

moment.js diff date formatting

I'm using moment.js and want to calculate the difference between two timestamp,format them afterwards and display them in a div.
var diffTime = moment(1390310146.791877).diff( 1390309386.271075);
This gives me 760 seconds, but I want to format it like this:
(days, hrs, mins, secs) and only show days, hours and seconds if they are higher than 0.
How do I achieve that ?
moment.duration should be used
let startTime = moment('09:45:20', 'h:mm:ss A').format("HH:mm:ss");
let endTime = moment('10:30:35', 'h:mm:ss A').format("HH:mm:ss")
var todayDate = moment(new Date()).format("MM-DD-YYYY"); //Can change, based on the requirement
var startDate = new Date(`${todayDate} ${startTime}`);
var endDate = new Date(`${todayDate} ${endTime}`);
var diffTime = moment(endDate).diff(startDate);
var duration = moment.duration(diffTime);
var years = duration.years(),
days = duration.days(),
months = duration.months(),
hrs = duration.hours(),
mins = duration.minutes(),
secs = duration.seconds();
var div = document.createElement('div');
div.innerHTML = years + ' years ' + months + 'months ' + days + ' days ' + hrs + ' hrs ' + mins + ' mins ' + secs + ' sec';
document.body.appendChild(div);
jsfiddle
try this
var diffTime = moment(moment(1390310146.791877).diff( 1390309386.271075)).format('H m s');
it will output "5 30 0"
Edit
here is the simple way to get the difference. for this both the time should be in the same timezone.
var a = moment(1390310146.791877);
var b = moment(1390309386.271075);
a.diff(b)//To get the difference in milliseconds
a.diff(b,'seconds')//To get the difference in seconds
a.diff(b,'minutes')//To get the difference in minutes
a.zone()//Get the timezone offset in minutes
hope this helps.

Categories

Resources