Return a formatted String from time in Java

Description

The following code shows how to return a formatted String from time.

Example


/*ww w.  j a  v a  2  s .co  m*/
/**
 * $Revision: 10205 $
 * $Date: 2008-04-11 15:48:27 -0700 (Fri, 11 Apr 2008) $
 *
 * Copyright (C) 2004-2008 Jive Software. All rights reserved.
 *
 * This software is published under the terms of the GNU Public License (GPL),
 * a copy of which is included in this distribution, or a commercial license
 * agreement with Jive.
 */

import java.util.Date;

/**
 * Utility class to peform common String manipulation algorithms.
 */
public class Main {
  public static void main(String[] argv) {
    System.out.println(getTimeFromLong(12312312312312L));
  }

  // Constants used by escapeHTMLTags
  private static final char[] QUOTE_ENCODE = """.toCharArray();
  private static final char[] AMP_ENCODE = "&".toCharArray();
  private static final char[] LT_ENCODE = "<".toCharArray();
  private static final char[] GT_ENCODE = ">".toCharArray();

  /**
   * Returns a formatted String from time.
   * 
   * @param diff
   *            the amount of elapsed time.
   * @return the formatte String.
   */
  public static String getTimeFromLong(long diff) {
    final String HOURS = "h";
    final String MINUTES = "min";
    final String SECONDS = "sec";

    final long MS_IN_A_DAY = 1000 * 60 * 60 * 24;
    final long MS_IN_AN_HOUR = 1000 * 60 * 60;
    final long MS_IN_A_MINUTE = 1000 * 60;
    final long MS_IN_A_SECOND = 1000;
    Date currentTime = new Date();
    long numDays = diff / MS_IN_A_DAY;
    diff = diff % MS_IN_A_DAY;
    long numHours = diff / MS_IN_AN_HOUR;
    diff = diff % MS_IN_AN_HOUR;
    long numMinutes = diff / MS_IN_A_MINUTE;
    diff = diff % MS_IN_A_MINUTE;
    long numSeconds = diff / MS_IN_A_SECOND;
    diff = diff % MS_IN_A_SECOND;
    long numMilliseconds = diff;

    StringBuffer buf = new StringBuffer();
    if (numHours > 0) {
      buf.append(numHours + " " + HOURS + ", ");
    }

    if (numMinutes > 0) {
      buf.append(numMinutes + " " + MINUTES);
    }

    // buf.append(numSeconds + " " + SECONDS);

    String result = buf.toString();

    if (numMinutes < 1) {
      result = "< 1 minute";
    }

    return result;
  }

}

The code above generates the following result.





















Home »
  Java Tutorial »
    Date »




Date Get
Date Set
Date Format
Date Compare
Date Convert
Date Calculation
Date Parse
Timezone