1 /* 2 * Copyright (C) 2018 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.documentsui.util; 18 19 import android.icu.text.MeasureFormat; 20 import android.icu.text.MeasureFormat.FormatWidth; 21 import android.icu.util.Measure; 22 import android.icu.util.MeasureUnit; 23 import android.text.format.DateUtils; 24 25 import java.util.Locale; 26 27 /** 28 * A utility class for formating different type of values to strings. 29 */ 30 public class FormatUtils { FormatUtils()31 private FormatUtils() {} 32 33 /** 34 * Returns the given duration in a human-friendly format. For example, 35 * "4 minutes" or "1 second". Returns only the largest meaningful unit of time, 36 * and the result duration will round to that unit. 37 * For example, 500 milliseconds round to 1 second, 38 * 90000 milliseconds (90 seconds or 1.5 minutes) round to 2 minutes. 39 * The returned unit of time is from seconds up to hours. 40 * This founction is copied from {@link DateUtils} 41 * @param millis the duration time in milliseconds. 42 * @return String of the duration. 43 */ formatDuration(long millis)44 public static String formatDuration(long millis) { 45 MeasureFormat formatter = MeasureFormat.getInstance(Locale.getDefault(), FormatWidth.WIDE); 46 if (millis >= DateUtils.HOUR_IN_MILLIS) { 47 final int hours = 48 (int) ((millis + DateUtils.HOUR_IN_MILLIS / 2) / DateUtils.HOUR_IN_MILLIS); 49 return formatter.format(new Measure(hours, MeasureUnit.HOUR)); 50 } else if (millis >= DateUtils.MINUTE_IN_MILLIS) { 51 final int minutes = 52 (int) ((millis + DateUtils.MINUTE_IN_MILLIS / 2) / DateUtils.MINUTE_IN_MILLIS); 53 return formatter.format(new Measure(minutes, MeasureUnit.MINUTE)); 54 } else { 55 final int seconds = 56 (int) ((millis + DateUtils.SECOND_IN_MILLIS / 2) / DateUtils.SECOND_IN_MILLIS); 57 return formatter.format(new Measure(seconds, MeasureUnit.SECOND)); 58 } 59 } 60 } 61