How create Date Object with values in java

Gotcha: passing 2 as month may give you unexpected result: in Calendar API, month is zero-based. 2 actually means March.

I don’t know what is an “easy” way that you are looking for as I feel that using Calendar is already easy enough.

Remember to use correct constants for month:

 Date date = new GregorianCalendar(2014, Calendar.FEBRUARY, 11).getTime();

Another way is to make use of DateFormat, which I usually have a util like this:

 public static Date parseDate(String date) {
     try {
         return new SimpleDateFormat("yyyy-MM-dd").parse(date);
     } catch (ParseException e) {
         return null;
     }
  }

so that I can simply write

Date myDate = parseDate("2014-02-14");

Yet another alternative I prefer: Don’t use Java Date/Calendar anymore. Switch to JODA Time or Java Time (aka JSR310, available in JDK 8+). You can use LocalDate to represent a date, which can be easily created by

LocalDate myDate =LocalDate.parse("2014-02-14");
// or
LocalDate myDate2 = new LocalDate(2014, 2, 14);
// or, in JDK 8+ Time
LocalDate myDate3 = LocalDate.of(2014, 2, 14);

Leave a Comment