简体   繁体   中英

How to show time in human readable format in Java?

I am making one logic, in one method I am getting time in milliseconds. I want to show it something like below:

if time is b/w 1 minutes - 60 minutes, lets say 25 minutes it will show - 25 minute
if time is 1 hour and 59 minutes it will show - 1h+
later if its 2 hour than it will show - 2h+
this will continue to 24 hour.
later if its one day and few hours than it will show - 1d+
this will be continue till week and later on week, months and year like 
    1h+..... 1d,
    1d+..... 1w,
    1w+..... 1m,
    1m+..... 1y, 1y+..

I cant use more if else. I need good performance with this method.

You can write few if's and create table for millisecond range, like using concurrenthashmap which has key and values. if your millisecond range fall in 0 to 60000 - milliseconds, create a seconds key and value in the hash map similarly with 60000 to 3600000, create a key of minute and value in it likewise you can proper ranges and it's values.

you can go with java.util.concurrent.TimeUnit class and it's method toSeconds(long duration),toMinutes(long duration),toHiurs(long duration)....to convert milliseconds to seconds,minutes,hours,days and so on.

Example: `TimeUnit.MILLISECONDS.toMinutes(millis);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM