简体   繁体   English

如何在Java中以人类可读的格式显示时间?

[英]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并创建毫秒范围的表,例如使用具有键和值的concurrenthashmap。 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. 如果您的毫秒范围落在0到60000毫秒之间,请在哈希映射中创建一个秒键和值,类似于60000到3600000,在其中创建一个分钟和值的键同样可以使用适当的范围和值。

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. 你可以使用java.util.concurrent.TimeUnit类,它的方法是秒(长持续时间),toMinutes(长持续时间),toHiurs(长持续时间)....将毫秒转换为秒,分钟,小时,天等等。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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