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 void main(String args[]) {
// Instantiate a Date object
Date date = new Date();
// display time and date using toString()
System.out.println(date.toString());
}
}
It compiles fine. But the output given is:
Date@15db9742
While i am expecting a output like this:
Mon May 04 09:51:52 CDT 2009
What is wrong with the code?
EDIT: I tried to rename the class.. The editted code:
import java.util.*;
public class DateDemo {
public static void main(String args[]) {
// Instantiate a Date object
Date d = new Date();
// display time and date using toString()
System.out.println(d.toString());
}
}
This is how I compiled the code and ran:
sou@sou-linux:~/Desktop/java$ javac DateDemo.java
sou@sou-linux:~/Desktop/java$ java DateDemo
The output is:
Date@15db9742
now() now() method of a LocalDate class used to obtain the current date from the system clock in the default time-zone. This method will return LocalDate based on system clock with default time-zone to obtain the current date.
The getTime() method of Java Date class returns the number of milliseconds since January 1, 1970, 00:00:00 GTM which is represented by Date object.
We can use now() method to get the current date. We can also provide input arguments for year, month and date to create LocalDate instance. This class provides an overloaded method for now() where we can pass ZoneId for getting dates in a specific time zone. This class provides the same functionality as java.
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With