Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17



Posted on 1999-07-08
Medium Priority
Last Modified: 2012-06-27
 I'm using Symmantic 3.0, developing a %100 pure java program. I want to be able to get the current time, and store it as a string - to be displayed to a GUI.
 example - I want a string to have "July 8, 1999, 09:50.56"

     (The format doesn't need to look the same)

What Would I use and How would I do it?

Question by:jcast17
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
1 Comment

Accepted Solution

vladi21 earned 200 total points
ID: 1245535
 8. (Sect. 8) How do you use the Date class to display the current time in
     my timezone?

     [*] There is more than one bug involving timezones, so some people have
     it working OK, but others trying something very similar are hitting
     other date format and timezone bugs. Before diving into the details,
     let's review the date-related classes.
        o Class Date represents a specific instant in time, with millisecond
          precision. The design of this class is a very bad joke - a
          sobering example of how even good programmers screw up.
        o Class Calendar is an abstract class for converting between a Date
          object and a set of integer fields such as year, month, day, and
        o Class GregorianCalendar is the only subclass of Calendar in the
          JDK. It does the Date-to-fields conversions for the calendar
          system in common use. Sun licensed this overengineered junk from
          Taligent - a sobering example of how average programmers screw up.
        o Class DateFormat is an abstract class that lets you convert a Date
          to a printable string with fields in the way you want (e.g.
          dd/mm/yy or dd.MMM.yyyy or whatever). DateFormat and
          SimpleDateFormat classes use the default timezone for your JVM.
          This is the JVM's "user.timezone" property (a more sensible choice
          would be to attempt to use the timezone of the underlying OS). If
          the "user.timezone" property is not set, it now defaults to GMT
          (not PST as it used to). A very small improvement. To associate
          the timezone of your choosing with a date format, use

            DateFormat df = DateFormat.getDateInstance();

          An alternative explanation says that the problem is that
          DateFormat uses the default Locale, which most likely has a
          different default TimeZone than the default TimeZone. Sun claims
          this is not a bug and that it is intended behaviour. The fix is as
        o Class TimeZone is an abstract class that represents a time zone
          offset, and also figures out daylight savings. GregorianCalendar
          tries to default to the timezone (if any) set in your Java system
          properties file. This timezone will be something like, e.g. "PST",
          "EST", "CET" etc.

          If there is no preset timezone, it used to default (prior to JDK
          1.1.2 or so) to PST - Pacific Standard Time as used in California.
          Since 1.1.2 the code now defaults to GMT when no timezone is in
          the properties file.

          The default timezone that Java starts with may well be wrong for
          your purposes. You are frequently better off if you explicitly set
          the default timezone (not much of a default, is it?) with

          TimeZone tsz = TimeZone.getTimeZone("ECT"); // use your timezone

          It is also possible to set a timezone not with a string, but
          according to a number of hours and minutes offset from the default
        o Class SimpleTimeZone is the only subclass of TimeZone in the JDK.
          It represents a timezone for use with a Gregorian calendar. This
          simple class does not handle historical changes, and has limited
          rules. When you ask for the default timezone, you'll actually get
          an object of this subclass back.

     If you want to see the properly formatted version of your Date, you
     shouldn't use myDate.getTime().toString(). A Date object now only
     represents an instant in time, resolved to the millisecond. All other
     uses (such as extracting individual fields or formatting) have been
     deprecated. To display the current date, declare a GregorianCalendar
     and pull the fields out of that, as in this example:

     import java.util.*;
     GregorianCalendar g = new GregorianCalendar();
     int year = g.get(Calendar.YEAR);
     int mon  = g.get(Calendar.MONTH);
     int date = g.get(Calendar.DATE);
     mon++; // in class Calendar & GregCal, months run 0-11 ;-(
     System.out.println(mon +"/" +date +"/" +year);

     If you want fancy formats for printing/expressing the date, you should
     use the new internationalization routines. You will need to use the
     DateFormat and SimpeDataFormat classes in the java.text package. Here
     is an example:

     import java.util.*;
     import java.text.*;

     Locale.setDefault( Locale.ENGLISH );
     DateFormat.getDateInstance(DateFormat.SHORT).format(new Date()));

     This will print (on April 7, 1998):


     There is some sample code in the Java API documentation. As an example
     of how the new method should work, jdk1.1/src/java/util/
     contains the method:

     DateFormat formatter = new SimpleDateFormat (
                        "d MMM yyyy HH:mm:ss 'GMT'", Locale.US);

     System.out.println( formatter.format(new Date()) );

     The last line results in output of: "7 Apr 1998 21:52:06 GMT"

     You can even use:


     It should be reasonably straightforward to adapt this code for your
     preferred format (e.g. change string to "hh:mm" or other) and timezone,
     e.g. change "GMT" to "ECT", "JST" or any other timezone.

  9. (Sect. 8) How are dates represented in Java?

     [*] java.util.Date stores dates as long integers representing the
     number of milliseconds since 00:00:00 UTC Jan 1, 1970 (the birth of
     Unix, a date known as the "Epoch"). Dates earlier than the Epoch are
     represented as negative numbers, counting away from 1/1/1970.

     The scheme is sufficient to represent dates from 292,269,053 B.C. to
     292,272,993 A.D. (64 bits covers -9223372036854775808 to
     +9223372036854775807 milliseconds, so divide by 1000 to get seconds,
     divide that by 3600*24*365.25 to get years, and you get -2.9227E8 to
     2.9227E8 centered on the Epoch i.e. about 292,269,053 B.C. to
     292,272,993 A.D.).

     In JDK 1.1, Date was augmented by Calendar. Things didn't get any
     better. Instead of being ill-conceived and simple, it is now
     ill-conceived and complicated. The poor code was all licensed from
     Taligent. Dates are the lemon of Java, as Roedy Green truly notes.

     You could consider using the BigDate class written by Roedy, and
     available at

 10. (Sect. 8) That may be, but how do I extract day, month, year from a

     [*] In JDK 1.1, Date represents an instant in time. Calendar translates
     between an instant in time, and individual fields like year, month,
     day, etc.

     So get your Date - the current Date can be had by

     Date now = new Date();

     Then construct a Calendar to do the translation:

     Calendar mycal = Calendar.getInstance();

     Now read the Calendar's fields using get().

     System.out.println("Year = " + mycal.get(Calendar.YEAR));

     We hope (perhaps in vain) all this junk will be fixed once and for all
     in a future release.

 11. (Sect. 8) How do I create my own Time Zone to apply to dates?

     [*] The Calendar, DateFormat, and even TimeZone classes will give you
     the timezone of your system (wherever you are). You can create a
     TimeZone object with the GMT offset of your choice like this:

     bst_tz = new SimpleTimeZone( 6 * 60 * 60 * 1000, // +6 hr from GMT

     You can then apply that TimeZone to create a Calendar object like so:

     GregorianCalendar BritishSummerTime =
              new GregorianCalendar(bst_tz);

 12. (Sect. 8) How do I create the BST timezone specifically? First, note
     the pitfall that as well as being the Bangkok Standard Time timezone 6
     hours east of GMT, "BST" also means "British Summer Time".

     In most or all other timezones, daylight savings time is handled
     automatically and internally. But GMT is the reference for all other
     timezones, and so does not have the summertime update applied
     automatically. So here is the code to create a British Summer Time
     timezone that is offset one hour from GMT between two dates:

     import java.util.*;
     import java.text.*;

     // BST runs from last Sun in March to 4th (not last) Sun in Oct

     // create a BST timezone (code courtesy of Tony Dahlman).
     SimpleTimeZone bst_tz =
        new SimpleTimeZone( 0, // no offset from GMT
                       "BST",  // individualized tz id
        Calendar.MARCH, -1, Calendar.SUNDAY,2*60*60*1000,  // 1st Sun Apr 2AM

        Calendar.OCTOBER, 4, Calendar.SUNDAY,2*60*60*1000  // 4th Sun Oct 2AM
     // set the BST timezone as the default

     // apply that TimeZone to create a Calendar object like so:
     GregorianCalendar BritishSummerTime =
          new GregorianCalendar(bst_tz,Locale.UK);

     and here is how you would print out values using BST:

     // create a template for printing the date
     DateFormat df = DateFormat.getTimeInstance(

     // tell the template to use BST tz.
     System.out.println("Using British Summer Time "
                       +"the time is: "
                       + df.format( BritishSummerTime.getTime() ) );

     // Now get and compare with current time in GMT
     df.setTimeZone(TimeZone.getTimeZone("GMT") );
     System.out.println("\nCurrent time in GMT is: "
                       + df.format(BritishSummerTime.getTime() ) );

     In the winter, this BST zone is aligned with GMT; in the summer it is
     one hour later (4 a.m. GMT is 5 a.m. BST).

     You can look at a list of timezone names and offsets in the file

 13. (Sect. 8) What kind of different date formats are allowed for the Date
     constructor with the string parameter?

     [*] That constructor is now deprecated, so you should not use it.

     Instead, you should convert a date/time String into a Date like this:

     // don't forget to set the default TZ if needed.
     DateFormat HHmm = new SimpleDateFormat( "HH:mm" );
     HHmm.setTimeZone( TimeZone.getDefault() );
     Date lunch = HHmm.parse( "12:30" );

     System.out.println( lunch );

     The above code would result in (when in the MST timezone),

     Thu Jan 01 12:30:00 MST 1970

     To parse other date and time fields, refer to the SimpleDateFormat


Featured Post

The top UI technologies you need to be aware of

An important part of the job as a front-end developer is to stay up to date and in contact with new tools, trends and workflows. That’s why you cannot miss this upcoming webinar to explore the latest trends in UI technologies!

Question has a verified solution.

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

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…
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 …
The viewer will learn how to implement Singleton Design Pattern in Java.
This tutorial will introduce the viewer to VisualVM for the Java platform application. This video explains an example program and covers the Overview, Monitor, and Heap Dump tabs.
Suggested Courses

704 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