Moment JS - Round up hours and limiting output to 2 decimals - javascript

Can't seem to find information about how to round up the result of my hours results. Looking only limiting the output to 2 decimals.
For example, the console.log below will provide me with 1.4166666666666667 but I would like if it would round up to 1.47 (maximum of 2 decimals).
var startTime = $('2016-02-21 18:00');
var endTime = $('2016-02-21 19:25');
var duration = moment.duration(moment(endTime, 'YYYY/MM/DD HH:mm').diff(moment(startTime, 'YYYY/MM/DD HH:mm')));
var hours = duration.asHours()
console.log(hours);
Would anyone know if this is possible using moment JS? I created an example of this script here https://jsfiddle.net/ewmq6sof/1/ if that would help.

The easiest thing to do is to just use .toFixed(2)
var hours = duration.asHours().toFixed(2)
If you always want to decimals, or use Math.round()
var hours = Math.round(duration.asHours() * 100) / 100
if you want a maximum of two decimals.
No need for moment here.

Related

Timesheet hours difference in moment.js

I have a string '08:30-16:30' describing working hours.
I also have the time someone has worked, in HH:mm format,eg.09:15
What is the easiest-fastest way to convert them in dates and find the difference in HH:mm format ?
Should i use Moment.js?
Also,i need the difference in minutes or seconds so that i can do comparisons with that.
I would be grateful if you could give me some examples.
For finding the difference between the working hours, you could make use of MomentJS.
Example:
var working_hours = '08:30-16:30';
var hours_arr = working_hours.split('-'); // Gives an array with ['08:30', '16:30']
var start = moment(hours_arr[0], "HH:mm");
var end = moment(hours_arr[1], "HH:mm");
var duration = moment.duration(end.diff(start));
var minutes = parseInt(duration.asMinutes());
The minutes variable would contain the difference in minutes.

Subtract time in 24 hour format using javascript or jquery

I have a start and end time in the format of HH:MM and I need to get the total time in hours. I have tried a couple methods like trimming the string to an hour and minutes then multiplying the hours by 60 and adding the minutes but since the minute string is two digits, 00 I get an answer that is a power of ten greater than what I need. I also feel like this approach is inefficient.
So what is the best way to subtract 04:30 and 22:00? I also have access to moment.js if that is helpful.
Using moment.js' difference
var a = moment('22:00', 'HH:mm');
var b = moment('04:30', 'HH:mm');
a.diff(b, 'hours', true)

get time different (minutes) in javascript

How do I calculate the difference in minutes given two strings. For example say I have
11:00
11:30
But of course the second string could be 12:11 so I can't subtract just the minutes.
first use javascript to convert the strings to time, then subtract, then convert back to strings
like this:
x = new Date("1/1/01 11:00")
y = new Date("1/1/01 11:30")
// now y-x has difference in milliseconds
// (y-x)/1000 is difference in seconds, etc
The data 1/1/01 is just being used as a dummy value, but the one thing you might have to worry about is are the times on different days, if so you will have to use 1/2/01 for the second time. Unless of course you always know the times are in the same day, but if they can cross "midnight" then you have to adjust for that.
You may want to use http://momentjs.com/ which will take care of the details for you.
When looking for getting metrics such as date , hour , minutes, seconds from the date difference, it's a lot easier to use basic notations as listed here
var x = new Date(new Date().getTime() + 11.5*60*60000); // adds 11 hours - 30 minutes
var y = new Date(new Date().getTime() + 11*60*60000); // adds 11 hours
alert(x.getMinutes() - y.getMinutes()); // gives the difference = 30
Here's an example : https://jsfiddle.net/DinoMyte/157knmgn/

need to find the difference between timings without dates in javascript application

In javascript application, I don't have Dates but only timings of a day in 24hrs format. How can I properly find the difference between them?
All my google search results are giving Date Time difference calculations only.
For example, If I want to find the difference between (4.15pm to 2.45 pm),
In my code I have,
var startTime = "14.45"; var endTime = "16.15";
Now var diffTime = endTime - startTime, which should give 1.30.
To get clarity on my question, you can refer my related question SO, to understand what I am trying to achieve.
Convert your string into the smallest unit required, which is minutes in your case. Do the arithmetic to get the result in minutes. Again do arithmetic to find hours and minutes from the result. You can also add logic to check if hours is zero and change to 24 in that case. But as comments point out, bare times cannot be compared if not of the same date.
function getMinutes(timeString){
var hours = parseInt(timeString.split('.')[0], 10);
hours = hours === 0? 24 : hours;
var minutes = parseInt(timeString.split('.')[1], 10);
var totalMinutes = (hours * 60) + minutes;
return totalMinutes;
}
var startTime = "23.45";
var endTime = "0.15";
var differenceInMinutes = getMinutes(endTime) - getMinutes(startTime);
var resultString = Math.floor(differenceInMinutes/60) + "." + (differenceInMinutes%60);
Another way can be by creating dummy dates using date constructor and keeping date part as some arbitrary date (same for end and start) and do common date comparison methods.
You seem to have 2 string variables in javascript. So talking about times and dates is really too early. They pretty much look like floating point numbers but if this was the case then the only arithmetic you could apply to floating point numbers is floating point arithmetic (+, -, *, /). So the first step for you would be to parse those string variables to the corresponding floating point numbers:
var startTime = '14.45';
var endTime = '16.15';
var startTimeFloat = parseFloat(startTime);
var endTimeFloat = parseFloat(endTime);
if (isNaN(startTimeFloat) || isNaN(endTimeFloat)) {
alert('Please input valid floating point numbers before being able to do any arithmetic on them');
} else {
var difference = endTimeFloat - startTimeFloat;
// Obviously here you should take into account the case where
// the start number is bigger than the end number in which case
// you would get a negative value for the difference. If you care only
// about the absolute value of the difference then you may use the
// Math.abs javascript method. Just like that:
// var difference = Math.abs(endTimeFloat - startTimeFloat);
alert(difference);
}

how to calculate number of days between today and given date and code for getTime()?

I want to calculate number of days between today and a given date and check whether how many days remaining until today or how many days past from today.
var today = new Date();
var date_to_reply = new Date('2012-10-15');
var timeinmilisec = today.getTime() - date_to_reply.getTime();
console.log( Math.floor(timeinmilisec / (1000 * 60 * 60 * 24)) );
this gives me 5 as answer but how should i get (-5) since the date_to_reply is 5days past from today?
is this the correct way to calculate any given date?
Regards
What you are doing is correct: You want to calculate the difference (as number of days) between two dates. A difference can't be smaller than zero.
Although your date_to_reply is already in the past, theres still a 5 day difference.
So, everythings fine - it's the correct way.
EDIT:
If you want a negative value as result, try this:
var today = new Date();
var date_to_reply = new Date('2012-10-15');
var timeinmilisec = date_to_reply.getTime() - today.getTime();
console.log( Math.ceil(timeinmilisec / (1000 * 60 * 60 * 24)) );
Remember you need to Math.ceil the final result instead of rounding it down with Math.floor().
If you want the value to be negative (indicating date_to_reply is in the past) you should subtract the past date from the current: date_to_reply.getTime() - today.getTime().
Check this link for ways to calculate more diffentiated results.
If you swap the order of the dates, you'll get the negative number you want.
Better yet you could write a function that does this.
It could subtract the first parameter from the second.
The second parameter could default to today.
function diffDates(dateOne, dateTwo) {
if (typeof dateTwo === 'undefined') {
dateTwo = new Date();
}
return dateOne.getTime() - dateTwo.getTime();
}
It would be better to have the function operate on numbers rather than dates.
That would be more flexible, but I'm typing on an iPad right now!
Its obvious because today's date is greater than the previous. So either you need to make it negative on your own or use this
var timeinmilisec = date_to_reply.getTime()-today.getTime();

Categories

Resources