Here you can find the source of getFriendlyTime(long duration)
Parameter | Description |
---|---|
duration | Time to convert |
public static String getFriendlyTime(long duration)
//package com.java2s; /******************************************************************************* * Copyright 2017 jamietech//from ww w . ja v a 2s. c om * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ import java.util.concurrent.TimeUnit; public class Main { /** * Gets a human-readable String containing the time. * @param duration Time to convert * @return Human-readable String */ public static String getFriendlyTime(long duration) { final StringBuilder sb = new StringBuilder(); long months = TimeUnit.MILLISECONDS.toDays(duration); if (months >= 30) { months = months / 30; duration -= TimeUnit.DAYS.toMillis(months * 30); } else { months = 0; } final long years = months / 12; if (years > 0) { months -= Math.floor(years * 12); duration -= TimeUnit.DAYS.toMillis(years * 365); } final long days = TimeUnit.MILLISECONDS.toDays(duration); duration -= TimeUnit.DAYS.toMillis(days); final long hours = TimeUnit.MILLISECONDS.toHours(duration); duration -= TimeUnit.HOURS.toMillis(hours); final long minutes = TimeUnit.MILLISECONDS.toMinutes(duration); duration -= TimeUnit.MINUTES.toMillis(minutes); final long seconds = TimeUnit.MILLISECONDS.toSeconds(duration); if (years > 0) { sb.append(" ").append(years); sb.append(" ").append(years == 1 ? "year" : "years"); } if (months > 0) { sb.append(" ").append(months); sb.append(" ").append(months == 1 ? "month" : "months"); } if (days > 0) { sb.append(" ").append(days); sb.append(" ").append(days == 1 ? "day" : "days"); } if (hours > 0) { sb.append(" ").append(hours); sb.append(" ").append(hours == 1 ? "hour" : "hours"); } if (minutes > 0) { sb.append(" ").append(minutes); sb.append(" ").append(minutes == 1 ? "minute" : "minutes"); } if (seconds > 0) { sb.append(" ").append(seconds); sb.append(" ").append(seconds == 1 ? "second" : "seconds"); } return sb.toString().trim(); } }