How to create a Date object for a specific date in Java

Creating a new date in Java is quite simple. Use the Calendar class to quickly create your Date object

//Generate a date for Jan. 9, 2013, 10:11:12 AM
Calendar cal = Calendar.getInstance();
cal.set(2013, Calendar.JANUARY, 9); //Year, month and day of month
Date date = cal.getTime();

If you also need to set the time, you can use the .set() method with the following parameters:

//Generate a date for Jan. 9, 2013, 10:11:12 AM
Calendar cal = Calendar.getInstance();
cal.set(2013, Calendar.JANUARY, 9, 10, 11, 12); //Year, month, day of month, hours, minutes and seconds
Date date = cal.getTime();

VoilĂ ! It’s that simple! If you are still getting to grips with the Java programming languages, I recommend Head First Java. It’s a nicely paced introduction to Java.

One comment on “How to create a Date object for a specific date in Java

  1. You need to do the cal.clear() call after getting the Instance. Otherwise, you will get left over seconds and milliseconds from current date and time.

    Calendar cal = Calendar.getInstance();
    cal.clear(); // <- you need this call

    cal.set(2013, Calendar.JANUARY, 9); //Year, month and day of month
    Date date = cal.getTime();

Leave a Reply

Your email address will not be published. Required fields are marked *

To create code blocks or other preformatted text, indent by four spaces:

    This will be displayed in a monospaced font. The first four 
    spaces will be stripped off, but all other whitespace
    will be preserved.
    
    Markdown is turned off in code blocks:
     [This is not a link](http://example.com)

To create not a block, but an inline code span, use backticks:

Here is some inline `code`.

For more help see http://daringfireball.net/projects/markdown/syntax