1 /* 2 * Copyright (C) 2023 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy 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, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 package com.android.settings.fuelgauge.batteryusage; 18 19 import java.util.Calendar; 20 21 /** A utility class for timestamp operations. */ 22 final class TimestampUtils { 23 getNextHourTimestamp(final long timestamp)24 static long getNextHourTimestamp(final long timestamp) { 25 final Calendar calendar = getSharpHourCalendar(timestamp); 26 calendar.add(Calendar.HOUR_OF_DAY, 1); 27 return calendar.getTimeInMillis(); 28 } 29 getNextEvenHourTimestamp(final long timestamp)30 static long getNextEvenHourTimestamp(final long timestamp) { 31 final Calendar calendar = getSharpHourCalendar(timestamp); 32 final int hour = calendar.get(Calendar.HOUR_OF_DAY); 33 calendar.add(Calendar.HOUR_OF_DAY, hour % 2 == 0 ? 2 : 1); 34 return calendar.getTimeInMillis(); 35 } 36 getLastEvenHourTimestamp(final long timestamp)37 static long getLastEvenHourTimestamp(final long timestamp) { 38 final Calendar calendar = getSharpHourCalendar(timestamp); 39 final int hour = calendar.get(Calendar.HOUR_OF_DAY); 40 calendar.add(Calendar.HOUR_OF_DAY, hour % 2 == 0 ? 0 : -1); 41 return calendar.getTimeInMillis(); 42 } 43 getNextDayTimestamp(final long timestamp)44 static long getNextDayTimestamp(final long timestamp) { 45 final Calendar calendar = getSharpHourCalendar(timestamp); 46 calendar.add(Calendar.DAY_OF_YEAR, 1); 47 calendar.set(Calendar.HOUR_OF_DAY, 0); 48 return calendar.getTimeInMillis(); 49 } 50 isMidnight(final long timestamp)51 static boolean isMidnight(final long timestamp) { 52 final Calendar calendar = Calendar.getInstance(); 53 calendar.setTimeInMillis(timestamp); 54 return calendar.get(Calendar.HOUR_OF_DAY) == 0 55 && calendar.get(Calendar.MINUTE) == 0 56 && calendar.get(Calendar.SECOND) == 0 57 && calendar.get(Calendar.MILLISECOND) == 0; 58 } 59 getSharpHourCalendar(final long timestamp)60 private static Calendar getSharpHourCalendar(final long timestamp) { 61 final Calendar calendar = Calendar.getInstance(); 62 calendar.setTimeInMillis(timestamp); 63 calendar.set(Calendar.MINUTE, 0); 64 calendar.set(Calendar.SECOND, 0); 65 calendar.set(Calendar.MILLISECOND, 0); 66 return calendar; 67 } 68 } 69