Solved

Time in Java

Posted on 2000-05-15
9
404 Views
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:

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.
0
Comment
Question by:lorus77
9 Comments
 
LVL 16

Expert Comment

by:imladris
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();
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
 
LVL 5

Expert Comment

by:sgoms
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,
sgoms
0
 
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"
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
 
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.

Jim
0
Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

 

Expert Comment

by:yoavdo
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 ?
0
 
LVL 1

Accepted Solution

by:
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

regards
karthic
0
 
LVL 1

Expert Comment

by:karthicraja
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

regards
karthic
0
 

Author Comment

by:lorus77
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.
0
 
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.
Jim
0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Are you developing a Java application and want to create Excel Spreadsheets? You have come to the right place, this article will describe how you can create Excel Spreadsheets from a Java Application. For the purposes of this article, I will be u…
Java Flight Recorder and Java Mission Control together create a complete tool chain to continuously collect low level and detailed runtime information enabling after-the-fact incident analysis. Java Flight Recorder is a profiling and event collectio…
Viewers will learn one way to get user input in Java. Introduce the Scanner object: Declare the variable that stores the user input: An example prompting the user for input: Methods you need to invoke in order to properly get  user input:
Viewers will learn about the regular for loop in Java and how to use it. Definition: Break the for loop down into 3 parts: Syntax when using for loops: Example using a for loop:

932 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

12 Experts available now in Live!

Get 1:1 Help Now