Time in Java

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:

Application.java:16: cannot resolve symbol
symbol  : method getHours  ()
location: class SwingApplication
            hours = getHours();
                        ^
Application.java:17: 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.
lorus77Asked:
Who is Participating?
 
karthicrajaCommented:
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

regards
karthic
0
 
imladrisCommented:
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();
hours=d.getHours();
mins=d.getMinutes();

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.
0
 
sgomsCommented:
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,
sgoms
0
Get your problem seen by more experts

Be seen. Boost your question’s priority for more expert views and faster solutions

 
Jim CakalicSenior Developer/ArchitectCommented:
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"
where:
    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
0
 
Jim CakalicSenior Developer/ArchitectCommented:
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.

Jim
0
 
yoavdoCommented:
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 ?
0
 
karthicrajaCommented:
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

regards
karthic
0
 
lorus77Author Commented:
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.
0
 
Jim CakalicSenior Developer/ArchitectCommented:
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.
Jim
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.