Time in Java

Posted on 2000-05-15
Last Modified: 2010-04-01
What is the best way to get a string that contains current system time? I tried to use getHours and getMins from java.util.* functions to get integers for hours and minutes but i got message: cannot resolve symbol
symbol  : method getHours  ()
location: class SwingApplication
            hours = getHours();
                        ^ cannot resolve symbol
symbol  : method getMins  ()
location: class SwingApplication
            mins = getMins();

Since I am a newbie in Java, I am not sure what it means. Please help.
Question by:lorus77
LVL 16

Expert Comment

ID: 2812286
getHours and getMins are methods of a particular class. The Date class, for instance, has such methods. To access them you must have a Date object. So for instance:

Date d=new Date();

These methods are deprecated, starting in 1.1. That means that the JVM writers don't think this is the best thing to use and, in the longer run, they may no longer be supported.
However, for now, rather than get into the description of the current recommended method, this should be OK.

Expert Comment

ID: 2812345
the methods in the Date class are deprecated. u can use,

Calendar cal=Calendar.getInstance(); //System date

int hr=cal.get(Calendar.HOUR_OF_DAY); //will give you the hour of the day
int mins=cal.get(Calendar.MINUTE);//will give u the mins

all the best,
LVL 19

Expert Comment

by:Jim Cakalic
ID: 2812364
java.util.Date encapsulates a time with millisecond resolution. A simple way of getting an output String with the date/time represented by a Date object is with its toString() method which returns a value in the form:
    "dow mon dd hh:mm:ss zzz yyyy"
    dow is the day of the week (Sun, Mon, Tue, Wed, Thu, Fri, Sat).
    mon is the month (Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec).
    dd is the day of the month (01 through 31), as two decimal digits.
    hh is the hour of the day (00 through 23), as two decimal digits.
    mm is the minute within the hour (00 through 59), as two decimal digits.
    ss is the second within the minute (00 through 61, as two decimal digits.
    zzz is the time zone (and may reflect daylight savings time).
    yyyy is the year, as four decimal digits.

Here is a code fragment showing how to get this kind of String value:

    Date date = new Date();
    String value = date.toString();

More sophisticated formatting of Date values is accomplished with DateFormat and SimpleDateFormat. DateFormat can produce a String value for a Date in the following styles (time and date style can be set independently):
    SHORT is completely numeric, such as 12.13.52 or 3:30pm
    MEDIUM is longer, such as Jan 12, 1952
    LONG is longer, such as January 12, 1952 or 3:30:32pm
    FULL is pretty completely specified, such as Tuesday, April 12, 1952 AD or 3:30:42pm PST.

Here is a code fragment showing how to use DateFormat to get a String value:

    Date date = new Date();
    DateFormat formatter = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.LONG);
    String value = formatter.format(date);

SimpleDateFormat extends DateFormate to give complete control over all date elements and their presentation by specification of a pattern. The pattern symbols are:

    Symbol   Meaning                 Presentation        Example
    ------   -------                 ------------        -------
    G        era designator          (Text)              AD
    y        year                    (Number)            1996
    M        month in year           (Text & Number)     July & 07
    d        day in month            (Number)            10
    h        hour in am/pm (1~12)    (Number)            12
    H        hour in day (0~23)      (Number)            0
    m        minute in hour          (Number)            30
    s        second in minute        (Number)            55
    S        millisecond             (Number)            978
    E        day in week             (Text)              Tuesday
    D        day in year             (Number)            189
    F        day of week in month    (Number)            2 (2nd Wed in July)
    w        week in year            (Number)            27
    W        week in month           (Number)            2
    a        am/pm marker            (Text)              PM
    k        hour in day (1~24)      (Number)            24
    K        hour in am/pm (0~11)    (Number)            0
    z        time zone               (Text)              Pacific Standard Time
    '        escape for text         (Delimiter)
    ''       single quote            (Literal)           '

Here are some examples (from the jdk documentation):

    Format Pattern                         Result
    --------------                         -------
    "yyyy.MM.dd G 'at' hh:mm:ss z"    ->>  1996.07.10 AD at 15:08:56 PDT
    "EEE, MMM d, ''yy"                ->>  Wed, July 10, '96
    "h:mm a"                          ->>  12:08 PM
    "hh 'o''clock' a, zzzz"           ->>  12 o'clock PM, Pacific Daylight Time
    "K:mm a, z"                       ->>  0:00 PM, PST
    "yyyyy.MMMMM.dd GGG hh:mm aaa"    ->>  1996.July.10 AD 12:08 PM
Here is a code fragment showing how to use SimpleDateFormat to get a String value:

    Date date = new Date();
    SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
    String value = formatter.format(date);

Best regards,
Jim Cakalic
LVL 19

Expert Comment

by:Jim Cakalic
ID: 2812371
Well, that came out lookin' like crap, didn't it? Hope its readable. If not, much of it came verbatim from the jdk documentation for Date, DateFormat, and SimpleDateFormat.

How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails


Expert Comment

ID: 2813164
System.currentTimeMillis() will give a long value of the system time.
after receiving system time (it's mili. sec. since jan 1 1970) u can construct a Date by :  Date(long time)is that what u wanted ?

Accepted Solution

karthicraja earned 50 total points
ID: 2813712
Calendar objects are best to use here

Calendar a = Calendar.getInstance();

String str = a.get(Calendar.DATE)+"/"+(a.get(Calendar.MONTH)+1)+"/"+a.get(Calendar.YEAR)+" : "+
            a.get(Calendar.HOUR)+ "h:"+a.get(Calendar.MINUTE)+"m:"+ a.get(Calendar.SECOND)+"s "+
            ((a.get(Calendar.AM_PM)==1) ? "PM":"AM" );

This will give you all you need


Expert Comment

ID: 2813715
Calendar objects are best to use here

Calendar a = Calendar.getInstance();

String str = a.get(Calendar.DATE)+"/"+(a.get(Calendar.MONTH)+1)+"/"+a.get(Calendar.YEAR)+" : "+
            a.get(Calendar.HOUR)+ "h:"+a.get(Calendar.MINUTE)+"m:"+ a.get(Calendar.SECOND)+"s "+
            ((a.get(Calendar.AM_PM)==1) ? "PM":"AM" );

This will give you all you need


Author Comment

ID: 2813983
karthicraja has given an simple and really good answer. It works. Thanks.

ummm jim, I'm using jdk 1.3 and it really looks like Date class has been depricated. Thanks for the lengthy answer anyway, at keast it explains the functionality of time in Java.
LVL 19

Expert Comment

by:Jim Cakalic
ID: 2815037
The Date class has most definitely _NOT_ been deprecated. Many of the methods in Date are deprecated because the responsibilities of the class changed and that behavior has been allocated to other classes. Here is the explanation given in the javadoc for Date:

"Prior to JDK 1.1, the class Date had two additional functions. It allowed the interpretation of dates as year, month, day, hour, minute, and second values. It also allowed the formatting and parsing of date strings. Unfortunately, the API for these functions was not amenable to internationalization. As of JDK 1.1, the Calendar class should be used to convert between dates and time fields and the DateFormat class should be used to format and parse date strings. The corresponding methods in Date are deprecated."

I'll admit to not really understanding your problem from the limited information in your post. However, as you can see from the above description, if your problem is extracting time fields, then Calendar is the appropriate class. (BTW, Calendar uses Date -- see the description in the jdk javadoc.) On the other hand, if you need to obtain a formatted String representation of a Date, then DateFormat and SimpleDateFormat would be more appropriate to solving your problem.

Glad you have a solution that works for you.

Featured Post

What Security Threats Are You Missing?

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

Join & Write a Comment

For customizing the look of your lightweight component and making it look lucid like it was made of glass. Or: how to make your component more Apple-ish ;) This tip assumes your component to be of rectangular shape and completely opaque. (COD…
Introduction This article is the second of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article covers the basic installation and configuration of the test automation tools used by…
Viewers will learn about the different types of variables in Java and how to declare them. Decide the type of variable desired: Put the keyword corresponding to the type of variable in front of the variable name: Use the equal sign to assign a v…
This tutorial explains how to use the VisualVM tool for the Java platform application. This video goes into detail on the Threads, Sampler, and Profiler tabs.

706 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

16 Experts available now in Live!

Get 1:1 Help Now