Tutorials About

Java Date and Time Tutorial

The Java date and time API's can be rather confusing when you first try to figure out how to use it. Therefore I have put together this little trail on Java's date and time classes. Hopefully that will help you get an overview of Java's date and time classes. I also hope it may clear up some of the confusion Sun has created with Java's many date and time classes.

Java has the following date and time classes and methods. Each of these classes are also explained in their own pages, later. See the links at the bottom of this page, or at the top right of every page.

System.currentTimeMillis() A static method that returns the current date and time as milliseconds since January 1st 1970
java.util.Date A class that represents a date and time. Most methods in this class is deprecated.
java.sql.Date A class that represents a date. All time information cut off. This date class is used with JDBC.
java.sql.Timestamp A class that represents a date and time. This date and time class is used with JDBC.
java.util.Calendar A base class for calendar classes. Has methods to do date and time arithmethics like adding a day or month to another date.
java.util.GregorianCalendar A concrete class subclassing java.util.Calendar, representing the Gregorian calendar which is used in most of the western world today. Has all the methods from java.util.Calendar to do date and time arithmethics.
java.util.TimeZone The Java TimeZone class is a class that represents time zones, and is helpful when doing calendar arithmetics across time zones.
java.text.SimpleDateFormat A class that can help you parse String's into Date's, and format Date's as String's.

So, which of all these classes should you use? Well, that depends on what you are trying to do.

If you need to do simple timing the System.currentTimeMillis() method will do just fine.

If you just need an object to hold a date, for instance as a property in a simple domain model object, you can use the java.util.Date class.

If you need to read and write the date and time to a database, use the java.sql.Date and java.sql.Timestamp classes.

If you need to do date calculations like adding days or months to another date, or check what weekday (monday, tuesday etc.) a given date is, or convert dates and times between time zones, use the java.util.Calendar and java.util.GregorianCalendar classes.

Here is a list of the texts in this Java date and time tutorial. This list also available in the upper right side of all pages, so you can easily navigate between them.

Connect with me: Newsletter - Get all my free tips!

Close TOC
This website uses cookies to improve the user experience and gather statistics. Our advertisers use cookies too (3rd party cookies), to provide more relevant ads. Continued use of this website implies that you accept the use of cookies on this website. We do not share our cookies with our advertisers, and our advertisers do not share cookies with us.