Click here to Skip to main content
15,884,298 members
Articles / Programming Languages / Java
Tip/Trick

Developing a TimeUtil Class to Work with Time in Java

Rate me:
Please Sign up or sign in to vote.
5.00/5 (1 vote)
25 Jun 2015CPOL2 min read 8.2K   2   4
Through this tip, we develop a Java class named TimeUtil to extend Java's built in Date class so we can work with local times in our application.

Introduction

In this tip, we develop a class named TimeUtil to work with Java’s built in Date class to obtain current time in two formats: GMT and our desired format.

Background

Java has many useful classes to work with times and dates. Two of them are frequently used today: Calendar and Date. In this text using the second one, Date, is the subject. Although it has many deprecated methods, we use one of its alive members called getTime() to implement the program.

Using the Code

As said before, we create a TimeUtil class at an instance level which means all of its members  are instance ones. The class has private members with public accessors (getters and setters) so behind the scenes there is a good abstraction and encapsulation.

It has just one constructor (absolutely you can extend it to has many) in which a Date object is instantiated and in turn getTime() invoked by it. The getTime() method is an instance method of the Date class which returns the number of milliseconds since January 1, 1970, 00:00:00 GMT (known as UNIX epoch).

All of the class logic is encapsulated in one method called localizer and also in getters.

To use the class in your apps, you must create an instance of that and set time offsets from GMT. Then call getters of your object to do what you want.

Additional notes are in code snippets below:

Java
package Main;
import java.util.Date;
/**
* @author MrSH :<code> </code><a href="http://www.thevelop.ir">thevelop.ir</a>
*/
Java
/** This class enables its user to show current time in two formats: GMT and user-local */
public class TimeUtil {
    /** Data field: current date */
    private Date curDate;
    /** Data field: current time in seconds */
    private long curTimeSeconds;
    /** Data field: current GMT time in seconds */
    private byte GMTSecond;
    /** Data field: current GMT time in minutes */
    private byte GMTMinute;
    /** Data field: current GMT time in hours */
    private byte GMTHour;
    /** Data field: current local time in seconds */
    private byte LocalSecond;
    /** Data field: current local time in minutes */
    private byte LocalMinute;
    /** Data field: current local time in hours */
    private byte LocalHour;
    /** Data field: hour offset */
    private byte hourOffset;
    /** Data field: minute offset */
    private byte minuteOffset;
    /** Default constructor */
    public TimeUtil(){
        curDate = new Date();
        curTimeSeconds = curDate.getTime()/1000;
    }
    /** Returns current GMT time in seconds
     * @return  current GMT time in seconds*/
    public byte getGMTSecond() {
        return (byte) (curTimeSeconds%60);
    }
    /** Returns current GMT time in minutes
     * @return current GMT time in minutes*/
    public byte getGMTMinute(){
        return (byte) (curTimeSeconds/60%60);
    }
    /** Return current GMT time in hours
       @return current GMT time in hours*/
    public byte getGMTHour(){
        return (byte) (curTimeSeconds/3600%24);
    }
    /** Set hour offset*/
    public void setHourOffset(byte hourOffset){
        this.hourOffset = hourOffset;
    }
    /** Returns hour offset
     * @return  hour offset*/
    public byte getHourOffset(){
        return hourOffset;
    }
    /** Set minute offset*/
    public void setMinuteOffset(byte minuteOffset){
        this.minuteOffset = minuteOffset;
    }
    /** Returns minute offset
     * @return  minute offset*/
    public byte getMinuteOffset(){
        return minuteOffset;
    }
    /** Returns current local time in seconds
     * @return  current local time in seconds*/
    public byte getLocalSecond(){
        return getGMTSecond();
    }
    /** Returns current local time in minutes
     * @return  current local time in minutes*/
    public byte getLocalMinute(){
        localizer();
        return LocalMinute;
    }
    /** Returns current local time in hours
     * @return  current local time in hours*/
    public byte getLocalHour(){
        localizer();
        return LocalHour;
    }
    /** Sets local time */
     private void localizer(){
        byte hourTemp = (byte) (getGMTHour() + getHourOffset());
        byte minuteTemp = (byte) (getGMTMinute() + getMinuteOffset());
        if(minuteTemp >= 60){
            LocalMinute = (byte) (minuteTemp%60);
            if(hourTemp + 1 >= 24){
                LocalHour = (byte) ((hourTemp + 1)%24);
            }
            else if (hourTemp + 1 < 0){
                LocalHour = (byte) (hourTemp + 24);
            }
            else
                LocalHour = (byte) (hourTemp + 1);
        }
        else if(minuteTemp < 0){
            LocalMinute = (byte) (minuteTemp + 60);
            if(hourTemp - 1 >= 24){
                LocalHour = (byte) ((hourTemp - 1)%24);
            }
            else if (hourTemp - 1 < 0){
                LocalHour = (byte) (hourTemp + 23);
            }
            else
                LocalHour = (byte) (hourTemp - 1);
        }
        else {
            LocalMinute = minuteTemp;
            if(hourTemp >= 24){
                LocalHour = (byte) (hourTemp%24);
            }
            else if (hourTemp < 0){
                LocalHour = (byte) (hourTemp + 24);
            }
            else
                LocalHour = hourTemp;
        }
    }
}

Some Tips and Notes

Using byte to store variables is for optimization purposes and speeding up performance.

Using javadoc comments /** */ will enable other programmers discover ideas in your code and make the program more readable. They can be extracted into an HTML file using the JDK’s javadoc command. For more information, see java.sun.com/j2se/javadoc.

Calling curTimeSeconds = curDate.getTime()/1000; in the constructor, we avoid calling it in all of our accessors. This is a huge improvement!

Feel free to develop. :)

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior) thevelop.ir
Iran (Islamic Republic of) Iran (Islamic Republic of)
I am a software professional with over 10 years of commercial business applications design and development experience.

My programming experience includes Java, Spring, Struts, JSF, Hibernate, EJB, Oracle, PHP, C, C++, HTML, CSS, JavaScript frameworks and libraries and Assembly.

In the last 6 years I am working with Java Technology and currently available to take up new assignments.

Comments and Discussions

 
Questionwhy not just use... Pin
Sacha Barber25-Jun-15 18:30
Sacha Barber25-Jun-15 18:30 
AnswerRe: why not just use... Pin
Salar Hafezi25-Jun-15 22:13
professionalSalar Hafezi25-Jun-15 22:13 
GeneralRe: why not just use... Pin
Sacha Barber25-Jun-15 22:21
Sacha Barber25-Jun-15 22:21 
AnswerRe: why not just use... Pin
Salar Hafezi26-Jun-15 5:25
professionalSalar Hafezi26-Jun-15 5:25 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.