Parsing date and running in static link to non-static method Error in java

I have a line in my main form:

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

Essentially, I want to scan in a date using .Scanner

Which gets to the error:

Cannot make static reference to non-static parse (String) method of type DateFormat

Now I looked into this error, but it does not seem as clear as this example .

How do I get around this?

+4
source share
6 answers

parse() not a static method. This is an instance method. You need to instantiate DateFormat and then call parse() on that instance:

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

The static method belongs to the class. It makes no sense to call Person.getName() . But it makes sense to call

 Person pureferret = new Person("Pureferret"); String name = pureferret.getName(); 
+6
source

As stated in the API Documentation :

 DateFormat df = DateFormat.getDateInstance(); myDate = df.parse(myString); 
+2
source

You need to instantiate DateFormat to call "parse". Only static methods can be called without initializing an instance of the specified class. You can get an instance calling DateFormat by default:

 DateFormat.getInstance() 

then you can call

 DateFormat.getInstance().parse() 

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

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

Check how you can configure it:

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

+2
source

DateFormat is an abstract class that needs a specific instance.

eg.

  DateFormat df = new SimpleDateFormat(...); 

Check out this example to learn how to use it.

+1
source

You can try this code:

 String format = "yyyy-MM-dd"; // put proper format here Date gameDate = new SimpleDateFormat(format).parse(scanner.nextLine()); 
+1
source

Parsing a method of the DateFormat class is not static. You must instantiate the DateFormat object before you can call its parsing method.

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

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

+1
source

All Articles