LP#1402797 browser client interval parser
[working/Evergreen.git] / Open-ILS / web / js / ui / default / staff / services / date.js
1 /**
2  * Core Service - egDate
3  *
4  * Date utility functions.
5  *
6  */
7 angular.module('egCoreMod')
8
9 .factory('egDate', function() {
10
11     var service = {};
12
13     /**
14      * Converts an interval string to seconds.
15      *
16      * egDate.intervalToSeconds('1 min 2 seconds')) => 62
17      * egDate.intervalToSeconds('2 days')) => 172800
18      * egDate.intervalToSeconds('02:00:23')) => 7223
19      */
20     service.intervalToSeconds = function(interval) {
21         var d = new Date();
22         var start = d.getTime();
23         var parts = interval.split(' ');
24
25         for(var i = 0; i < parts.length; i += 2)  {
26
27             if (!parts[i+1]) {
28                 // interval is a bare hour:min:sec string
29                 var times = parts[i].split(':');
30                 d.setHours(d.getHours() + Number(times[0]));
31                 d.setMinutes(d.getMinutes() + Number(times[1]));
32                 d.setSeconds(d.getSeconds() + Number(times[2]));
33                 continue;
34             }
35
36             var count = Number(parts[i]);
37             var type = parts[i+1].replace(/s?,?$/,'');
38
39             if (type.match(/^s/)) {
40                 d.setSeconds(d.getSeconds() + count);
41             } else if (type.match(/^min/)) {
42                 d.setMinutes(d.getMinutes() + count);
43             } else if (type.match(/^h/)) {
44                 d.setHours(d.getHours() + count);
45             } else if (type.match(/^d/)) {
46                 d.setDate(d.getDate() + count);
47             } else if (type.match(/^mon/)) {
48                 d.setMonth(d.getMonth() + count);
49             } else if (type.match(/^y/)) {
50                 d.setFullYear(d.getFullYear() + count);
51             }
52         }
53
54         return Number((d.getTime() - start) / 1000);
55     }
56
57     return service;
58 })
59
60
61