Time

     

The following class contains methods for formatting times in ways you are likely to want to do.

Times.java

 

 package net.dates; import java.util.*; import java.text.*; public class Times {  Calendar calendar = Calendar.getInstance();     public static void main(String...a) {     log(get24HourTime() );     log(getAMPMTime() );     log( getSimpleTime() );   } /**     * Returns time in this format:     * 14.36.33     */    public static String get24HourTime() {    Date d = new Date();    Format formatter = new SimpleDateFormat("HH.mm.ss");    return formatter.format(d);    }    /**     * Returns time in this format:     * 01:12:53 AM     */    public static String getAMPMTime() {    Format formatter = new SimpleDateFormat("hh:mm:ss a");    return formatter.format(new Date());    }    public static String getSimpleTime() {       Format formatter = new SimpleDateFormat("h:mm a");          return formatter.format(new Date());    } public int getHour() {       return calendar.get(Calendar.HOUR_OF_DAY);    }    public int getMinute() {       return calendar.get(Calendar.MINUTE);    }    public int getSecond() {       return calendar.get(Calendar.SECOND);    }    public String getTime() {       return getHour() + ":" + getMinute() + ":" +              getSecond();    }       //will print out anything we pass it       //just a convenience    private static <T> void log(T msg) {       System.out.println(msg);    } } 

Running this class outputs something like this, depending on what time it is:

 

 18.25.04 06:25:04 PM 6:25 PM 

This class not only offers some utility methods that you can put to use in your own applications, but it makes use of the Format class and its subclasses in the java.text package (such as SimpleDateFormat). I recommend checking out the API documentation for these classes to find out about more usage options.



Java Garage
Java Garage
ISBN: 0321246233
EAN: 2147483647
Year: 2006
Pages: 228
Authors: Eben Hewitt

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net