javatimersimpledateformatelapsedtime

Display elapsed time with month an day support in JAVA


I need to display elapsed time in my application form.
I currently do this using this code:

    AppTimer = new Timer();
    AppTimer.scheduleAtFixedRate(new java.util.TimerTask() {
        SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
        public void run() {
            sdf.setTimeZone(java.util.TimeZone.getTimeZone("GMT+0"));
            lblAppRunTime.setText(""+sdf.format(new Date(AppTimeCounter*1000)));
            AppTimeCounter++;
        }
    },1000, 1000);

This Code shows hours,minutes & seconds properly but how can I show DAYS & MONTHS? new SimpleDateFormat("M D HH:mm:ss") can't do this and for example when 5 seconds elapsed it shows 1 month and 1 days too!

How can I show month and day too?

Thanks


Solution

  • You should not use the Date class for it, because a date is an instant of time, but you are using it as a duration. Please read carefully joda time documentation about it. And then you could use Period and PeriodFormatter for you task. Or write something similar if you don't want use the library.