I want to print current date and time in java..This is the code I am trying from a java tutorial:
import java.util.*;
public class Date {
public static
You are getting the default toString()
from Object
because you created your own class named Date
which is hiding the imported Date
from java.util.
. You can rename your class or you can use the canonical name java.util.Date like
public static void main(String args[]) {
java.util.Date date = new java.util.Date();
System.out.println(date);
}
Output here is
Mon Nov 03 10:57:45 EST 2014
Your class name is Date so
Date date = new Date();
will create an object of your class and when you call date.toString()
it will be the default Object.toString()
method.
So if you have to use the java.util.Date
class, rename your Date
class to something else
You could keep the code as simple as ::
import java.util.*;
public class Today{
public static void main(String args[]){
System.out.println("System Date :: ");
System.out.println(new Date());
}
}
As well as change the class name to today or something else but not Date as it is a keyword
You can try this,
import java.util.Date;
public class CurrentDate
{
public static void main(String[] args)
{
Date currentDate = new Date();
System.out.println("Curent Date and Time - " + currentDate.toString());
}
}
Output:
Mon May 04 09:51:52 CDT 2009
Also, you can refer links below on date and time formatting. Quite useful.
https://docs.oracle.com/javase/tutorial/datetime/iso/datetime.html
https://docs.oracle.com/javase/7/docs/api/java/sql/Date.html
https://www.flowerbrackets.com/date-time-java-program/
Rename your class from Date to something else .. The following then works just as expected:
import java.util.Date;
public class ImplClass
{
public static void main(String args[])
{
Date date = new Date();
// display time and date using toString()
System.out.println(date.toString());
}
}
The output is in the desired format
Mon Nov 03 09:49:57 CST 2014
Your class is a custom class that is producing the output given by Object.toString
. Rename the class to something else other than Date
so that java.util.Date
is correctly imported