Java Date/Calendar example: How to get today’s date (now)

Java Date/Calendar FAQ: How do I get an instance of today's date with Java? (A Java Date to represent “now”).

Although you’re strongly encouraged not to get today’s date using the Date class, like this:

Date today = new Date();

you can still get today’s date in Java using one line of code with the Java Calendar class, like this:

// the correct way to get today's date
Date today = Calendar.getInstance().getTime();

This code can be read as, “Create an instance of a Java Calendar, which defaults to the current date and time; then use the getTime method to convert this to a java.util.Date reference.”

There are other ways to do this that are similar to this approach, but I believe this is the correct way to get an instance of today’s date, i.e., a date to represent “now”.

A complete Java “get today’s date” example

For the sake of completeness — and to help you experiment — here’s the source code for a complete Java class which demonstrates this technique of getting today’s date (a “now” date):

import java.util.*;

/**
 * A Java Date and Calendar example that shows how to
 * get today's date ("now").
 * 
 * @author alvin alexander, devdaily.com
 */
public class JavaGetTodaysDateNow
{

  public static void main(String[] args)
  {
    // create a calendar instance, and get the date from that
    // instance; it defaults to "today", or more accurately,
    // "now".
    Date today = Calendar.getInstance().getTime();
    
    // print out today's date
    System.out.println(today);
  }

}

As I write this article, the output from this class is:

Tue Sep 22 07:59:07 EDT 2009

I’ll add some more tutorials out here about using the Java Date and Calendar classes, including how to format dates, and perform date “math,” but for now, if you just need to get today’s date, I hope this helps.

(Update: Here’s a link to a very similar example that also demonstrates the Java SimpleDateFormat class: How to get today’s date in Java.)