JavaRanch Home    
 
This page:         last edited 21 June 2012         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.



  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-2013 Paul Wheaton