4

I have a line in my main like so:

Date gameDate = DateFormat.parse(scanner.nextLine());

Essentially I want to scan in a date with util.Scanner

Which hits the error:

Cannot make a static reference to the non-static method parse(String) from the type DateFormat

Now, I've looked in to this error, but it doesn't seem as clear cut as this example.

How do I get round this?

AncientSwordRage
  • 7,086
  • 19
  • 90
  • 173

6 Answers6

8

parse() is not a static method. It's an instance method. You need to create a DateFormat instance, and then call parse() on this instance:

DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
Date gameDate = dateFormat.parse(scanner.nextLine());

A static method belongs to a class. It doesn't make sense to call Person.getName(). But it makes sense to call

Person pureferret = new Person("Pureferret");
String name = pureferret.getName();
JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
2

As mentioned in the API Documentation:

DateFormat df = DateFormat.getDateInstance();
myDate = df.parse(myString);
Eng.Fouad
  • 115,165
  • 71
  • 313
  • 417
2

You have to create an instance of DateFormat in order to call "parse". Only static methods can be called without istantiating an instance of the specified class. You can get an instance with the default DateFormat calling:

DateFormat.getInstance()

then you can call

DateFormat.getInstance().parse()

or you can define your own DateFormat using for example a subclass of DateFormat, as SimpleDateFormat.

DateFormat myFormat = new SimpleDateFormat("yyyy-MM-dd");
myFormat.parse(myString);

Check here how you can customize it:

http://docs.oracle.com/javase/1.4.2/docs/api/java/text/SimpleDateFormat.html

JayZee
  • 851
  • 1
  • 10
  • 17
1

DateFormat is an abstract class that needs a concrete instantiation.

e.g.

   DateFormat df = new SimpleDateFormat(...);

Check out this example to see how to use it.

Brian Agnew
  • 268,207
  • 37
  • 334
  • 440
1

You can try this code:

String format = "yyyy-MM-dd"; // put proper format here
Date gameDate = new SimpleDateFormat(format).parse(scanner.nextLine());
Danilo Valente
  • 11,270
  • 8
  • 53
  • 67
Erich Schreiner
  • 2,038
  • 1
  • 14
  • 24
1

The method parse of the class DateFormat is not static. You must instantiate a DateFormat object first before you can call it's parse method.

You also must configure the "rules" of your date format so the parser knows what and how to parse.

See SimpleDateFormat class: http://docs.oracle.com/javase/6/docs/api/java/text/SimpleDateFormat.html

Filipe Palrinhas
  • 1,235
  • 8
  • 9