Want to win a PS4? Go Premium and enter to win our High-Tech Treats giveaway. Enter to Win

x
?
Solved

Time in Java

Posted on 2000-05-15
9
Medium Priority
?
426 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
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
VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

 
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
 

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 200 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

Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

Question has a verified solution.

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

Introduction This article is the last of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article covers our test design approach and then goes through a simple test case example, how …
In this post we will learn how to connect and configure Android Device (Smartphone etc.) with Android Studio. After that we will run a simple Hello World Program.
Viewers learn about the “for” loop and how it works in Java. By comparing it to the while loop learned before, viewers can make the transition easily. You will learn about the formatting of the for loop as we write a program that prints even numbers…
Viewers will learn how to properly install Eclipse with the necessary JDK, and will take a look at an introductory Java program. Download Eclipse installation zip file: Extract files from zip file: Download and install JDK 8: Open Eclipse and …
Suggested Courses

609 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