JavaRanch Home    
 
This page:         last edited 17 February 2014         What's Changed?         Edit

Java Date and Time FAQ   

When working with dates in Java, don't forget that a lot of questions can likely be answered by reading various class documentations. A few of the ones that are used frequently include Date, DateFormat, SimpleDateFormat, and Calendar:

Follow the links below for information on dealing with some common Date-related programming issues.

If you perform a lot of date-time operations, you might want to check out the Joda Time library. And Java 8 contains an entirely new data and time API in the java.time package, developed under JSR 310.



  Understanding Date objects, formatting and parsing

People sometimes ask questions about working with Date objects, specifically about how to convert a string that contains a date to a Date object, or how to display a date in a certain format. For example, they might ask: "How do I create a Date object in the format yyyy-MM-dd?", or "Why does Java print my Date in the format 'Fri Jun 28 09:16:39 CEST 2013', while I wanted '2013-06-28'?". Or they wonder how they can convert their Date object from one format to another. Questions like these come out of a lack of understanding what a Date object actually is and how to format and parse dates.

Here are a number of things to understand about Date objects.

1. The only thing that a Date object contains is a timestamp, represented as a number of milliseconds since 01-01-1970, 00:00:00 GMT. A Date object contains no other information. Specifically, Date objects do not have a format by themselves.

2. Converting a Date object to a String is called formatting, and converting a String to a Date object is called parsing.

3. To format a Date into a String, or parse a String into a Date, you use a DateFormat object. Class DateFormat is an abstract class; class SimpleDateFormat is the most well-known and easiest to use concrete subclass.

4. The DateFormat class is the only thing that knows the format you want to use. When you parse a String into a Date object, the Date object does not remember anything about the format that the String was in. A Date is just a Date, just like a number is just a number; it doesn't have an inherent format.

5. When you print a Date object "directly" (by explicitly or implicitly calling toString() on it), it will be printed using a default format, that will make it look like 'Fri Jun 28 09:16:39 CEST 2013'. You cannot change that default format. If you want it to be displayed in a different format, you need to format it using a DateFormat object.



  Parsing a string into a date

Parsing a String to a Date can be done with the DateFormat class. Note that you must include the seconds in the time in order for the LONG format to work. Also, you cannot use getTimeInstance with a string that includes anything other than a time, such as the date and time in d1, below:


DateFormat dflong = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.FULL);
    
DateFormat dfshort = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT);

DateFormat dfmedium = DateFormat.getDateInstance(DateFormat.MEDIUM);

Date d1 = dflong.parse("January 12, 2005 5:59:00 PM PST");
Date d2 = dfshort.parse("5/2/05 9:34 AM");
Date d3 = dfmedium.parse("Jul 12, 2005");

String s1 = dflong.format(d1);

System.out.printf("Long Date/time is %s \n",s1);

s1 = dfshort.format(d2);

System.out.printf("Short Date/time is %s \n",s1);

s1 = dfmedium.format(d3);

System.out.printf("Medium Date is %s \n",s1);

If you only want to check for validity, or don't want to catch the ParseException, DateFormat has a second parse method that takes a ParsePosition:


DateFormat dfmedium = DateFormat.getDateInstance(DateFormat.MEDIUM);

ParsePosition position = new ParsePosition(0);
Date d = dfmedium.parse("Jul 12, 2005", position);
if (d == null)
{
    // the date is invalid
}


  Formatting dates

If you want to format a Date into a String according to a format you want, you can use the SimpleDateFormat class. A simple example:


Date date = new Date();

// Specify the desired format here.
// See the javadocs of the SimpleDateFormat class for all the possibilities.
String formatString = "dd-MMM-YYYY";

// Create an instance of SimpleDateFormat
SimpleDateFormat dateFormat = new SimpleDateFormat(formatString);

// The parameter should be a Date and it returns the date formatted as a String object.
String outputDate = dateFormat.format(date);


  Daylight Savings Time

This is a snippet of code that will convert from BST (British Summer Time) to GMT:


TimeZone tzEL = TimeZone.getTimeZone("Europe/London");
TimeZone tzGMT = TimeZone.getTimeZone("GMT0");

TimeZone.setDefault(tzGMT);

String date = "04/21/2004 10:00:00"//10am BST

SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss");
sdf.setTimeZone(tzEL);
Date d = sdf.parse(date);

System.out.println(d); //This will output 9am GMT


  How many days in a given month?

A little code snippet that calculates the number of days in a particular month, taking leap years into account.


/**
 * Calculates the number of days in a given month.
 * @param m The month (a number from 1 to 12)
 * @param y The year (must have 4 digits)
 * @return int  The number of days in the month
 */
public static int getDaysInMonth (int m, int y) {
    int days = 31;
    if (m==4 || m==6 || m==9 || m==11) {
        days=30;
    } else if (m==2) {
        if (((y % 4)==0) && ((y % 100)!=0) || ((y % 400)==0))
            days=29;
        else
            days=28;
    }
    return days;
}

/**
 * Returns the number of days in the month in which "dt" happens to be.
 */
public static int getDaysInMonth (Date dt) {
    return getDaysInMonth(dt.getMonth() + 1, dt.getYear() + 1900);
}

Although the above works, java.util.Calendar has built-in support for this without hard-coding the number of days:


public static int getDaysInMonth (int m, int y) {
    Calendar calendar = new GregorianCalendar(y, m, 1);
    return calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
}


  Deprecated methods in java.util.Date

Do not shy away from java.util.Date just because it contains plenty of deprecated methods. They aren't deprecated because they produce incorrect results, but because a more powerful API is available with java.util.Calendar and its associated classes. If Date does what you need, you may wish to avoid the comparatively more complex Calendar class.

Note that Date objects do not have an associated timezone, though, so if you need to work with dates from different timezones, Calendar is a better choice. Also, Calendar takes Daylight Savings Time into account, whereas Date does not - that's important if you want to perform arithmetic on dates/times.


CategoryFaq

JavaRanchContact us — Copyright © 1998-2014 Paul Wheaton