Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Date constructor java

Tags:

java

date

Hello I am trying to get the current date at java at a Class I created but everything fails. I've seen in many sites e.g. http://www.mkyong.com/java/java-date-and-calendar-examples/ that the date constructor has no arguments e.g. Date date = new Date();

Now in my project I try to use it like this and I get the error

that The constructor Date() is undefined

How is this possible? I give you the full code so far

import java.sql.Date;
import java.text.SimpleDateFormat;


public class Utility {


        String title;
        int ID;
        Date date;

        Utility(String t,int ID){
            this.ID=ID+1;
            title=t;
            SimpleDateFormat sdf = new SimpleDateFormat("dd/M/yyyy");
            Date a=new Date();// I get the error here
            String date = sdf.format(a);
            System.out.print(date);


        }
}

I work at Eclipse IDE. Can you help me?

like image 974
JmRag Avatar asked Dec 23 '13 13:12

JmRag


3 Answers

The examples you found are for java.util.Date while you are using java.sql.Date

  • java.sql.Date

    has two constructors

    • Date(long date): Constructs a Date object using the given milliseconds time value.
    • Date(int year, int month, int day): which is deprecated

    and no default Date() constructor.

  • java.util.Date

    among others has a default constructor without arguments

    • Date(): Allocates a Date object and initializes it so that it represents the time at which it was allocated, measured to the nearest millisecond.

When importing classes, Eclipse will help you fining possible candidates but always check if the first suggestion is really what you want.

like image 200
Matteo Avatar answered Oct 15 '22 11:10

Matteo


You are using the wrong Date class.

Have a look at your imports. Don't use java.sql.Date use java.util.Date instead.

like image 36
Matthias Avatar answered Oct 15 '22 11:10

Matthias


You are importing java.sql.Date use java.util.Date

like image 23
kdabir Avatar answered Oct 15 '22 13:10

kdabir