So I'm just learning Javascript and I'm trying to create a calculator that can subtract time. I have the other parts working (although I'd love feedback on my code there as I'm sure it can be majorly improved on), I just need to get the time subtracting right. I'm doing simple math so when I subtract 1:30 (hours and minutes are separate values) from 2:00 it gives me 1:30 instead of just 00:30.
Another problem is the gold per hour doesn't calculate unless I hit the 'Get Results' button twice....
This is the first script I have ever written so please let me know what I should be doing, I want to do this the best and easiest way possible.
Calculator and script are here:
http://www.coolestwebsiteintheuniverse.com/gold-calculator/
http://www.coolestwebsiteintheuniverse.com/gold-calculator/calc.js
I'd also like the ability to expand it to 10 rows and average all of them but I think I could figure that out on my own once this part is figured out.
Thanks
Have you tried using date function to subtract.??
var T1=new Date("September 5, 2012 8:10:00");
var T2=new Date("September 5, 2012 13:35:00");
var diff=new Date();
diff.setTime(T2-T1);
alert(diff.getHours()+":"+diff.getMinutes())
The problem is that you're treating the hours separate from the minutes in making time calculations. You need to combine them with something like this (untested):
var starthh = // ...
var startmm = // ...
var endhh = // ...
var endmm = // ...
var elapsedMinutes = (60 * endhh + endmm) - (60 * starthh + startmm)
var displayTime = Math.floor(elapsedMinutes / 60) + ":"
+ ("00" + (elapsedMinutes % 60)).slice(-2)
That last bit, ("00" + (elapsedMinutes % 60)).slice(-2) takes the minutes modulo 60, appends it to the string "00" and then takes the last two charactes, as a quick way to zero pad single-digit numbers.
Related
I guess, this is some beginner question, but I don't know, what to search for.
I have a timesheet which should look like this:
From | To | Pause | Hours
[08:00] [17:30] [01:00] 08:30
The values in brackets (08:00, 17:30, 01:00) are input fields, the hours should be a calculated value.
So this is my form:
<div ng-repeat="t in timesheetCurrentMonth">
From: <input type="text" ng-model="t.from"/> <!-- e.g. 08:00 -->
To: <input type="text" ng-model="t.to"/> <!-- e.g. 17:30 -->
Pause:<input type="text" ng-model="t.pause"/><!-- e.g. 01:00 -->
Working hours:<span>{{t.to-t.from-t.pause|hhmm}}</span> <!-- e.g. 08:30 -->
</div>
So how can I enter date values into the textfields like '08:30' and calculate the total working hours?
I was thinking about calculating with minute values (08:00 = 480) in the model, because I will persist these data as minute values in the database and it makes the calculation simple (to-from-pause). Does that make sense? BTW, I do have a filter, that converts minute values into the HH:mm format.
Thanks,
Bernhard
PS: Here's a function that converts minutes (like 480) to an HH:MM string (08:00).
var convertToHourString = function(min, alwaysShowMinutes) {
var hours = Math.floor(min / 60);
var minutes = min % 60;
if (minutes === 0 && !alwaysShowMinutes)
return hours;
return hours + ":" + (minutes < 10 ? "0" + minutes : minutes);
};
momentJs provides all the date/time operations and convertions you need.
I would do the math inside of your controller as a calculated property. You will need to create a new Date() with the strings that are being passed in before you can do the math.
Here's a quick example: https://jsfiddle.net/khpfvo1u/
var start = new Date('2015-05-20 08:30:00');
var end = new Date('2015-05-20 15:30:00');
var result = (end - start) / 1000 / 60 / 60;
alert(result);
Like Michael said, momentJS will give you far richer functionality for anything to do with dates. If you have anything beyond very simple math it's probably worth introducing the dependency.
Ok, I've found it out by myself.
That was the question.
"So how can I calculate the total working hours?"
<span>{{calcWorkingHours(t.to, t.from, t.pause)|hhmm}}</span>
Scope: from=08:00, to=17:30, pause=01:00
So the variables to, from and pause will be converted into minute values, the working hours will be calculated (again as minute value) and outputted using a filter ('hhmm'), which converts sth. like 510 (minutes) into '08:30' hours.
I'm talking about two durations (e.g., "2 hours, 4 minutes" + "7 hours, 2 minutes"); not two timestamps. I googled this for a while and everything I could find was talking about calculating the differences between dates.
I'm using SQL, PHP and JavaScript; my database has a list of events with their durations, and I want to be able to sum up the total duration from a SELECT statement. The obvious solution is to substring the time, saying
total secs = first two chars*60*60 + second two chars*60 + last two chars
then multiply total secs by 60*60 to get a duration in decimal hours, round it down and keep the remainder for HH:mm... but that seems messy. Is there a cleaner, more proper solution I should be using?
you should change field "time" to "int"
Times can be added by converting to a common unit (say minutes in this case), add the mintues, then convert back to hours and minutes.
If you have a string like "2 hours, 4 minutes" you can convert it to minutes using something like:
function stringToMinutes (s) {
var a = s.match(/\d+/g);
return a[0]*60 + +a[1];
}
Convert back to hours and minutes like:
function minutesToString(m) {
function addS(n) {return n!= 1? 's' : '';}
var hr = m / 60 |0;
var min = m % 60;
return hr + ' hour' + addS(hr) + ', ' + min + ' minute' + addS(min);
}
This question already has answers here:
Convert HH:MM:SS string to seconds only in javascript
(14 answers)
Closed 8 years ago.
I need to compare the run times of marathon runners, im having difficulty comparing the run times as they are in the following format; 00:31:26, 00:34:29 (Hours:Minutes:Seconds).
Ideally I would like to convert the whole time into minutes so that I could then use the times to create a graph.
How could I convert the race times into a number using javascript or otherwise?
This example demonstrates Array.split to split the string into components, hours, minutes and seconds which are held in the variable array. It then uses parseInt to convert the component strings into an integer, which are then in turn mathematically multiplied and added together to give you a representation in seconds.
var time = "01:32:29";
var array = time.split(":");
var seconds = (parseInt(array[0], 10) * 60 * 60) + (parseInt(array[1], 10) * 60) + parseInt(array[2], 10)
console.log(seconds);
On jsfiddle
Same basic method, more succinctly
'02:04:03'.split (':').reduce (function (seconds, v) {
return +v + seconds * 60;
}, 0) / 60;
The split creates an array, the reduce and its function calculates the time in seconds, which is finally divided by 60 to get minutes as a floating point number. The result of the above is 124.05.
Without a library, I would use something like this
convertToMinutes = function(timeString) {
var hms = timeString.split(':');
return Math.ceil(parseInt(hms[2])/60) + parseInt(hms[1]) + parseInt(hms[0])*60
}
demo
http://jsbin.com/awiyir/1/edit
It's also possible to use the built in Date object. Then you can use built in functions for calculations, formatting etc.
Since Date is a date and not a simple time, I suggest aligning it with unix time. Then .getTime() will get the correct number of milliseconds.
var time1 = new Date ('01 01 70 00:31:26 UTC');
var time2 = new Date ('01 01 70 00:29:15 UTC');
var timediff=time1-time2; // Gets the time diff in millisecs
It is a bit hackish, but it works well.
More about the Date object: https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Date
First you need to convert into seconds as you have your time in hh:mm:ss. If you convert direct to minutes, you may not get exact time. You need to implement it this way :
Example :
var hms = '03:09:56'; // your input string
var a = hms.split(':'); // split it at the colons
// minutes are worth 60 seconds. Hours are worth 60 minutes.
var seconds = (+a[0]) * 60 * 60 + (+a[1]) * 60 + (+a[2]);
//if you want hours
var minutes = (seconds)/60;
console.log(minutes);
I'm trying to convert 15:00 (15minutes) to seconds though I get 54,000 when I use this below.
I'm trying to convert 15minutes to seconds.
S = '15:00';
D = "1/1/1 "
s = ( new Date(D+S) - new Date(D) )/1000
alert(s);
Though when I do the math, it's 60 x 15 = 900. How do I get 900, since the time is a random string.
Well if your format will always be "mm:ss" you could dome string parsing and do the math manually, of course this would need to be adjusted depending on the input format.
S = '15:25';
var times = S.split(":");
var minutes = times[0];
var seconds = times[1];
seconds = parseInt(seconds, 10) + (parseInt(minutes, 10) * 60);
alert(seconds);
Note in the example I explicitly added 25 seconds just as demonstration.
http://jsfiddle.net/Jg4gB/
The time string '15:00' in JavaScript refers to the time of day 1500hr, or 3:00 p.m. American-style. That's 15 hours after midnight. That explains why you got 54,000 seconds.
If you wanted to express 15 minutes using your method of manipulating date strings, try '00:15:00'.
I know there have been a lot of topics like this but I just have problem to which I couldn't find the answer.
My script is:
window.onload = function(){
// 200 seconds countdown
var countdown = 14400;
//current timestamp
var now = Date.parse(new Date());
//ready should be stored in your cookie
if ( !document.cookie )
{
document.cookie = Date.parse(new Date (now + countdown * 1000)); // * 1000 to get ms
}
//every 1000 ms
setInterval(function()
{
var diff = ( document.cookie - Date.parse(new Date()) );
if ( diff > 0 )
{
var message = diff/1000 + " seconds left";
}
else
{
var message = "finished";
}
document.body.innerHTML = message;
},1000);
}
I want to make countdown timer which tells user time how much left depending on his cookie value. So far I managed to calculate difference between two values but I don't know how to make format like, let's say, "dd/mm/yy hh:mm:ss" from difference timestamp (diff). Is it possible at all?
What you want is a function that converts difference in (mili)seconds to something like
5d 4h 3m 2s
If you don't mind having a large number of days for times periods > a few months, then you could use something like this:
function human_time_difference(diff) {
var s = diff % 60; diff = Math.floor(diff / 60);
var min = diff % 60; diff = Math.floor(diff / 60);
var hr = diff % 24; diff = Math.floor(diff / 24);
var days = diff;
return days + 'd ' + hr + 'h ' + min + 'm ' + s + 's';
}
If you have the difference in miliseconds, you'll need to pass the that number divided by 1000. You can also use Math.round to get rid of fractions, but you could just as well leave them on if you want that information displayed.
Getting months and years is a little trickier for a couple of reasons:
The number of days in a month varies.
When you're going from the middle of one month to the middle of the next, the time span doesn't cover any whole months, even if the number of days > 31 (e.g. How many months are there between the 2nd of June and the 30th of July??).
If you really want the number of months between two times, the number of seconds between them is not enough. You have to use calendar logic, which requires passing in the start and end date + time.
PS: When you post a question, avoid irrelevant details. For example, your question has nothing to do with cookies, setInterval, or onload handlers. The only part that you don't know is how to convert (mili)seconds to days, hours, etc. It might be helpful to supply some background on why you're trying to do something, but if it's not essential to understand the basic question, put it at the end so that people don't have to wade through it before getting to the essential part. The same advice applies to your title; make sure it's relevant by excluding irrelevant details (e.g. cookies and counting down).
JavaScript doesn't have any built in date formatting methods like you might expect if you've done any PHP. Instead, you have to build the string manually. However, there are a number of getter methods that will be useful to this end. See 10 ways to format time and date using JavaScript.
Also, just so you know. Date.parse doesn't return the millisecond portion of the time stamp (it rounds down). If you need the milliseconds, you can do either of the following
var d = new Date();
var timestamp_ms = Date.parse(d) + d.getMilliseconds();
or just
var timestamp_ms = +d;
I do not understand why you check the cookie by if ( !document.cookie ) But it doesnot work on my browser so I modified it into if ( document.cookie )
Try toString function and other. Look them up in javascript Date object reference. For example,
var t = new Date;
t.setTime(diff);
var message = t.toTimeString() + " seconds left";
This will print 11:59:58 seconds left on my browser.