简体   繁体   中英

AngularJS: input field with date

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提供您需要的所有日期/时间操作和转换。

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM