-1

I wanted to use the util.Date class in Java, but when I tried to instantiate a Date object, I realized that all the constructors that I can understand--the simple ones--were gone. All deprecated.

Can anybody tell me how I can make use of Date class?

Here is my code.

Constructor:

public Company(int id, String name, Date foundationDate) {
    super();
    this.id = id;
    this.name = name;
    this.foundationDate = foundationDate;
}

TestClass:

Company[] companies = new Company[3];
companies[0] = new Company(1, "Sabanci", new Date(12,12,12));
Saro Taşciyan
  • 5,210
  • 5
  • 31
  • 50
Bedir Yilmaz
  • 3,823
  • 5
  • 34
  • 54

3 Answers3

6

This constructor has been deprecated since Java 1.1 (a long time ago) From the javadoc

Date(int year, int month, int date)

Deprecated.

As of JDK version 1.1, replaced by Calendar.set(year + 1900, month, date) or GregorianCalendar(year + 1900, month, date).

As for the vastly superior JODA Time approach (from JavaDoc):

new DateTime(2012,12,12,0,0);
Community
  • 1
  • 1
Jason Sperske
  • 29,816
  • 8
  • 73
  • 124
4

If you want to use standard Java classes and you want to avoid deprecated methods (which is a good idea), then you can use the java.util.Calendar class. As stated in the comments, the JODA Time library is much easier to use, but Calendar is built in.

To create the Date December 12, 2012:

Calendar cal = Calendar.getInstance();
cal.clear();
cal.set(2012, Calendar.DECEMBER, 12);
Date date = cal.getTime();

You end up with a java.util.Date. Obviously, you can create a convenience method to build the Calendar object and just return the Date.

Brigham
  • 14,395
  • 3
  • 38
  • 48
1

Starting with Java 1.8 you can now also use the standard time library.

import java.time.LocalDate;
LocalDate myDate = LocalDate.of( 2012 , 12 , 12 );  // ( year , month , day-of-month )

Or parse a String.

LocalDate myDate = LocalDate.parse("2012-12-12");
Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
Josh Morel
  • 1,201
  • 12
  • 17