How can I calculate a time span in Java and format

2019-01-02 21:11发布

I want to take two times (in seconds since epoch) and show the difference between the two in formats like:

  • 2 minutes
  • 1 hour, 15 minutes
  • 3 hours, 9 minutes
  • 1 minute ago
  • 1 hour, 2 minutes ago

How can I accomplish this??

17条回答
谁念西风独自凉
2楼-- · 2019-01-02 21:44

Formatting time spans in java pops up for me frequently in ETL or DB pulls. The following code snippet is how I get the pulse of the operation.

    SimpleDateFormat ymdhms=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    DecimalFormat formatter = new DecimalFormat("#,###"); /* ("#,###.00"); gives you the decimal fractions */
    int counter=0;
    Date beginTime0=new Date();
    while (<some end condition>) {

        <some time consuming operation>

        /*// uncomment this section durring initial exploration of the time consumer
        if(counter>100000){
            System.out.println("debug exiting due to counter="+counter);
            System.exit(0);
        }
        */

        if(0==counter%1000){
            Date now = new Date();
            long diffInSeconds = (now.getTime() - beginTime0.getTime()) / 1000;
            long diff[] = new long[] { 0, 0, 0, 0 };
            diff[3] = (diffInSeconds >= 60 ? diffInSeconds % 60 : diffInSeconds);                        /* sec   */ 
            diff[2] = (diffInSeconds = (diffInSeconds / 60)) >= 60 ? diffInSeconds % 60 : diffInSeconds; /* min   */ 
            diff[1] = (diffInSeconds = (diffInSeconds / 60)) >= 24 ? diffInSeconds % 24 : diffInSeconds; /* hours */ 
            diff[0] = (diffInSeconds = (diffInSeconds / 24));                                            /* days  */ 
            String delta = String.format(
                "%s%s%s%s"
                ,(diff[0]>0?String.format("%d day%s "    ,diff[0],(diff[0]!=1?"s":"")):"")
                ,(diff[1]>0?String.format("%2d hour%s "  ,diff[1],(diff[1]!=1?"s":" ")):"")
                ,(diff[2]>0?String.format("%2d minute%s ",diff[2],(diff[2]!=1?"s":" ")):"")
                ,           String.format("%2d second%s ",diff[3],(diff[3]!=1?"s":" "))
            );
            System.out.println(String.format(
                "%12s %s delta= %s"
                ,formatter.format(counter)
                ,ymdhms.format(new Date())
                ,delta
                )
            );
        }
        counter++;
    }
查看更多
素衣白纱
3楼-- · 2019-01-02 21:45

This question is old and already has an answer but i have a better solution. Use relativeSpan from date utils

                dateHere.setText(DateUtils.getRelativeTimeSpanString(timeInMillis,
                        System.currentTimeMillis(), DateUtils.SECOND_IN_MILLIS));

it takes arguments: long/int time, current time and how you want it, _month,minute,second etc

查看更多
人气声优
4楼-- · 2019-01-02 21:46

I'd recommend you have a look at HumanTime

查看更多
呛了眼睛熬了心
5楼-- · 2019-01-02 21:47

I always start with Joda Time. Working with dates and times in Java is always "fun" but Joda Time takes the strain off.

They have Interval and Duration classes which do half of what you are looking for. Not sure if they have a function for outputing in readable format though. I'll keep looking.

HTH

查看更多
忆尘夕之涩
6楼-- · 2019-01-02 21:47
long time1, time2;
time1 = System.currentMillis();

.. drink coffee

time2 = System.currentMillis();

long difference = time2 - time1 // millies between time1 and time2

java.util.Date differneceDate = new Date(difference);

To create a string like "2 Minutes" you should use DateFormatter/DateFormat. You can find more details on this in the the Java API spec (java.sun.com).

查看更多
登录 后发表回答