1 /** 2 * Copyright (C) 2014 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); you may not 5 * use this file except in compliance with the License. You may obtain a copy 6 * of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 12 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 13 * License for the specific language governing permissions and limitations 14 * under the License. 15 */ 16 package com.android.server.usage; 17 18 import android.app.usage.UsageStatsManager; 19 20 /** 21 * A handy calendar object that knows nothing of Locale's or TimeZones. This simplifies 22 * interval book-keeping. It is *NOT* meant to be used as a user-facing calendar, as it has 23 * no concept of Locale or TimeZone. 24 */ 25 public class UnixCalendar { 26 private static final long DAY_IN_MILLIS = 24 * 60 * 60 * 1000; 27 private static final long WEEK_IN_MILLIS = 7 * DAY_IN_MILLIS; 28 private static final long MONTH_IN_MILLIS = 30 * DAY_IN_MILLIS; 29 private static final long YEAR_IN_MILLIS = 365 * DAY_IN_MILLIS; 30 private long mTime; 31 UnixCalendar(long time)32 public UnixCalendar(long time) { 33 mTime = time; 34 } 35 truncateToDay()36 public void truncateToDay() { 37 mTime -= mTime % DAY_IN_MILLIS; 38 } 39 truncateToWeek()40 public void truncateToWeek() { 41 mTime -= mTime % WEEK_IN_MILLIS; 42 } 43 truncateToMonth()44 public void truncateToMonth() { 45 mTime -= mTime % MONTH_IN_MILLIS; 46 } 47 truncateToYear()48 public void truncateToYear() { 49 mTime -= mTime % YEAR_IN_MILLIS; 50 } 51 addDays(int val)52 public void addDays(int val) { 53 mTime += val * DAY_IN_MILLIS; 54 } 55 addWeeks(int val)56 public void addWeeks(int val) { 57 mTime += val * WEEK_IN_MILLIS; 58 } 59 addMonths(int val)60 public void addMonths(int val) { 61 mTime += val * MONTH_IN_MILLIS; 62 } 63 addYears(int val)64 public void addYears(int val) { 65 mTime += val * YEAR_IN_MILLIS; 66 } 67 setTimeInMillis(long time)68 public void setTimeInMillis(long time) { 69 mTime = time; 70 } 71 getTimeInMillis()72 public long getTimeInMillis() { 73 return mTime; 74 } 75 truncateTo(UnixCalendar calendar, int intervalType)76 public static void truncateTo(UnixCalendar calendar, int intervalType) { 77 switch (intervalType) { 78 case UsageStatsManager.INTERVAL_YEARLY: 79 calendar.truncateToYear(); 80 break; 81 82 case UsageStatsManager.INTERVAL_MONTHLY: 83 calendar.truncateToMonth(); 84 break; 85 86 case UsageStatsManager.INTERVAL_WEEKLY: 87 calendar.truncateToWeek(); 88 break; 89 90 case UsageStatsManager.INTERVAL_DAILY: 91 calendar.truncateToDay(); 92 break; 93 94 default: 95 throw new UnsupportedOperationException("Can't truncate date to interval " + 96 intervalType); 97 } 98 } 99 } 100