AngularJS: input field with date - javascript

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.

Related

JavaScript - check if input date is within add 7 days from current yyyy/mm/dd date, NOT js date()

I have a form submit with 2 date inputs: share_start and share_end in yyyy-mm-dd format. I use JS to validate the input and want to check whether share_end date is within 7 days from the share_start date.
Now, the tricky bit is that I don't have a JS date() dates/timestamps, but only those input dates, but when trying to add on 7 days to the input in JS all I end up with an error since JS needs to operate with date(). I cannot use any external scripts like moment.js to help with this.
Does JS have some sort of in-built function like PHPs strtotime where I can just add + 7 days or something?
Thank you
// Form Submit Validation
function validateForm() {
var share_start = '2021-05-07';
var share_end = '2021-05-15';
var share_max = share_start.setDate(date.getDate() + 6);
if (share_end > share_max) {
alert("Share End Date cannot be more than 7 days from now");
return false;
}
}
At last figured it out.... Bloody JS date conversion is really a pain without libraries such moments.js
var date1 = '2021-01-01';
var date2 = '2021-01-08';
var diffTime = Math.abs(date2 - date1);
var diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));
if (diffDays > 6) {
alert("Share cannot be longer than 6 days");
return false;
}
In my particular case, I am getting the date values from a variable, which I then calculate the difference in seconds, after which I convert those seconds to days. Followed by a simple if statement where I check if the value is greater than x days, and I am good to go.

Calculate workingdays between 2 days javascript [duplicate]

This question already has answers here:
exclude weekends in javascript date calculation
(6 answers)
Calculate working days between two dates in Javascript excepts holidays
(10 answers)
Closed 1 year ago.
I know this question is asked a lot of times. And i did my research, but i really don't understand it. I just started using javascript.
This is my code to calculate days between the two inputs.. I erased my attempts to calculate weekend.
function GetDays(){
var datefrom = new Date(document.getElementById("datefrom").value);
var dateto = new Date(document.getElementById("dateto").value);
return parseInt((dateto - datefrom) / (1000 * 60 * 60 * 24));
}
function cal(){
if(document.getElementById("dateto")){
document.getElementById("numdays2").innerHTML=GetDays();
}
}
An answer in PHP is also good for me.
Hope someone can help me.
You should really make your function with parameters, so that the function can be unaware of input/output details and does not have to reference document.
Also, it is a habit to start function names with a lowercase letter unless it is a constructor (which is not the case here).
As to the algorithm: move the two given dates to the Sunday that precedes them (unless they already are Sundays). As getDay() returns 0 for Sunday, you can just subtract the getDay() number of days from the date, and it will be a Sunday. Remember how many working days you subtracted like that.
Then when both dates are Sundays, calculate the number of weeks between them and multiply this by 5 (working days).
Finally adjust this number by adding and subtracting the days you altered the dates with in order to make them align with Sunday.
Here is an interactive snippet:
function getDays(datefrom, dateto) {
datefrom = new Date(datefrom);
dateto = new Date(dateto);
let before = datefrom.getDay();
datefrom.setDate(datefrom.getDate() - before); // Go to previous Sunday
if (before) before--; // should be in {0,1,2,3,4,5}
let after = dateto.getDay();
dateto.setDate(dateto.getDate() - after); // Go to previous Sunday
if (after == 6) after--; // should be in {0,1,2,3,4,5}
// Count each 7 day difference as 5 days, and compensate for the changes to Sundays:
return Math.round((dateto - datefrom) / (1000 * 60 * 60 * 24)) / 7 * 5 + after - before
}
document.addEventListener("input", function () {
var datefrom = new Date(document.getElementById("datefrom").value);
var dateto = new Date(document.getElementById("dateto").value);
document.getElementById("numdays2").textContent = getDays(datefrom, dateto);
});
From: <input type="date" id="datefrom" value="2021-01-01"><br>
To: <input type="date" id="dateto" value="2021-01-01"><br>
Number of working days: <span id="numdays2">1</span>

How to convert time e.g. 00:31:26 into a number in javascript [duplicate]

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);

Simple javascript time/money per hour calculator

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.

Countdown timer with cookies

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.

Categories