072bc0efc65e2e0d631f3e550022f7cfca17d773
[platform/framework/web/crosswalk-tizen.git] /
1 var clone = require('../lang/clone');
2
3     /**
4      * get a new Date object representing start of period
5      */
6     function startOf(date, period){
7         date = clone(date);
8
9         // intentionally removed "break" from switch since start of
10         // month/year/etc should also reset the following periods
11         switch (period) {
12             case 'year':
13                 date.setMonth(0);
14             /* falls through */
15             case 'month':
16                 date.setDate(1);
17             /* falls through */
18             case 'week':
19             case 'day':
20                 date.setHours(0);
21             /* falls through */
22             case 'hour':
23                 date.setMinutes(0);
24             /* falls through */
25             case 'minute':
26                 date.setSeconds(0);
27             /* falls through */
28             case 'second':
29                 date.setMilliseconds(0);
30                 break;
31             default:
32                 throw new Error('"'+ period +'" is not a valid period');
33         }
34
35         // week is the only case that should reset the weekDay and maybe even
36         // overflow to previous month
37         if (period === 'week') {
38             var weekDay = date.getDay();
39             var baseDate = date.getDate();
40             if (weekDay) {
41                 if (weekDay >= baseDate) {
42                     //start of the week is on previous month
43                     date.setDate(0);
44                 }
45                 date.setDate(date.getDate() - date.getDay());
46             }
47         }
48
49         return date;
50     }
51
52     module.exports = startOf;
53
54