Newsletter sign-up
View all newsletters

Sign up for our technology specific newsletters.

Enterprise Java
Email Address:

Calculating Java dates

Take the time to learn how to create and use dates

  • Digg
  • Reddit
  • SlashDot
  • Stumble
  • del.icio.us
  • Technorati
  • dzone

Page 2 of 5

 
import java.util.*;
import java.text.*;
public class StyleDemo {
   public static void main(String[] args) {
      Date now = new Date();
      DateFormat df =  DateFormat.getDateInstance();
      DateFormat df1 = DateFormat.getDateInstance(DateFormat.SHORT);
      DateFormat df2 = DateFormat.getDateInstance(DateFormat.MEDIUM);
      DateFormat df3 = DateFormat.getDateInstance(DateFormat.LONG);
      DateFormat df4 = DateFormat.getDateInstance(DateFormat.FULL); 
      String s =  df.format(now);
      String s1 = df1.format(now);
      String s2 = df2.format(now);
      String s3 = df3.format(now);
      String s4 = df4.format(now);
      System.out.println("(Default) Today is " + s);
      System.out.println("(SHORT)   Today is " + s1);
      System.out.println("(MEDIUM)  Today is " + s2);
      System.out.println("(LONG)    Today is " + s3);
      System.out.println("(FULL)    Today is " + s4);
   }
}


That program output the following:

(Default) Today is Nov 8, 2000
(SHORT)   Today is 11/8/00
(MEDIUM)  Today is Nov 8, 2000
(LONG)    Today is November 8, 2000
(FULL)    Today is Wednesday, November 8, 2000


The same program, after being run on my computer with the default regional settings changed to Swedish, displayed this output:

(Default) Today is 2000-nov-08
(SHORT)   Today is 2000-11-08
(MEDIUM)  Today is 2000-nov-08
(LONG)    Today is den 8 november 2000
(FULL)    Today is den 8 november 2000      


From that, you can see that in Swedish the months of the year are not capitalized (although November is still november). Also, note that the LONG and FULL versions are identical in Swedish, while they differ in American English. Additionally, it is interesting that the Swedish word for Wednesday, onsdag, is not included in the FULL version, where the English FULL version includes the name of the day.

Note that you can use the getDateInstance method to change the language for a DateFormat instance; however, in the case above, it was done on a Windows 98 machine by changing the regional settings from the control panel. The lesson here is that the default regional setting varies from place to place, which has both advantages and disadvantages of which the Java programmer should be aware. One advantage is that the Java programmer can write a single line of code to display a date, yet have the date appear in tens or even hundreds of different forms when the program is run on computers throughout the world. But that can be a disadvantage if the programmer wants just one format -- which is preferable, for example, in a program that outputs text and dates mixed together. If the text is in English, it would be inconsistent to have dates in other formats, such as German or Spanish. If the programmer relies on the default regional format, the date format will vary according to the executing computer's regional settings.

Parsing a String

You can also use the DateFormat class to create Date objects from a String, via the parse() method. This particular method can throw a ParseException error, so you must use proper error-handling techniques. A sample program that turns a String into a Date is shown below:

 
import java.util.*;
import java.text.*;
public class ParseExample {
   public static void main(String[] args) {
      String ds = "November 1, 2000";
      DateFormat df = DateFormat.getDateInstance();
      try {
         Date d = df.parse(ds);
      }
      catch(ParseException e) {
         System.out.println("Unable to parse " + ds);
      }
   }
}


The parse() method is a useful tool for creating arbitrary dates. I will examine another way of creating arbitrary dates. Also, you will see how to do elementary calculations with dates, such as calculating the date 90 days after another date. You can accomplish both tasks with the GregorianCalendar class.

The GregorianCalendar class

One way to create an object representing an arbitrary date is to use the following constructor of the GregorianCalendar class, found in the java.util package:

 
GregorianCalendar(int year, int month, int date) 


Note that for the month, January is 0, February is 1, and so on, until December, which is 11. Since those are not the numbers most of us associate with the months of the year, programs will probably be more readable if they use the constants of the parent Calendar class: JANUARY, FEBRUARY, and so on. So, to create an object representing the date that Wilbur and Orville Wright first flew their motored aircraft (December 17, 1903), you can use:

 
GregorianCalendar firstFlight = new GregorianCalendar(1903, Calendar.DECEMBER, 17);  


For clarity's sake, you should use the preceding form. However, you should also learn how to read the shorter form, below. The following example represents the same December 17, 1903, date (remember, in the shorter form 11 represents December):

 
GregorianCalendar firstFlight = new GregorianCalendar(1903, 11, 17);   


In the previous section, you learned how to turn Date objects into Strings. You will do the same again; but first, you need to convert a GregorianCalendar object to a Date. To do so, you will use the getTime() method, which GregorianCalendar inherits from its parent Calendar class. The getTime() method returns a Date corresponding to a GregorianCalendar object. You can put the whole process of creating a GregorianCalendar object, converting it to a Date, and getting and outputting the corresponding String in the following program:

 
import java.util.*;
import java.text.*;
public class Flight {
   public static void main(String[] args) {
      GregorianCalendar firstFlight = new GregorianCalendar(1903, Calendar.DECEMBER, 17);    
      Date d = firstFlight.getTime();
      DateFormat df = DateFormat.getDateInstance();
      String s = df.format(d);
      System.out.println("First flight was " + s);
   }
}


Sometimes it is useful to create an instance of the GregorianCalendar class representing the day the instance was created. To do so, simply use the GregorianCalendar constructor taking no arguments, such as:

 
GregorianCalendar thisday = new GregorianCalendar();


A sample program to output today's date, starting with a GregorianCalendar object is:

 
import java.util.*;
import java.text.*;
class Today {
   public static void main(String[] args) {
      GregorianCalendar thisday = new GregorianCalendar();       Date d = thisday.getTime();
      DateFormat df = DateFormat.getDateInstance();
      String s = df.format(d);
      System.out.println("Today is " + s);
   }
}


Note the similarities between the Date() constructor and the GregorianCalendar() constructor: both create an object, which in simple terms, represents today.

  • Digg
  • Reddit
  • SlashDot
  • Stumble
  • del.icio.us
  • Technorati
  • dzone
Comments (11)
Login
Forgot your account info?

great manBy Anonymous on October 7, 2009, 11:51 amgreat man

Reply | Read entire comment

Very HelpfulBy Anonymous on October 7, 2009, 2:50 amThe article is so straight to the point and helpful

Reply | Read entire comment

greatBy Anonymous on September 3, 2009, 1:58 amtoday thanks to your group sir.

Reply | Read entire comment

great articleBy Anonymous on July 5, 2009, 11:41 pmThis descriptive article helped me understand the date function and the coding examples helped me see how it works. Great article!

Reply | Read entire comment

Good. Thnx.By Anonymous on July 4, 2009, 11:37 amGood. Thnx.

Reply | Read entire comment

View all comments

Add comment
Anonymous comments subject to approval. Register here for member benefits.
Have a JavaWorld account? Log in here. Register now for a free account.
Resources