Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

print current date in java

Tags:

java

time

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

like image 873
SouvikMaji Avatar asked Nov 03 '14 15:11

SouvikMaji


People also ask

What is now () in Java?

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.

What does date () getTime () do in Java?

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.

How do I get the current date in Java 8?

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.


2 Answers

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

like image 100
Reimeus Avatar answered Nov 03 '22 06:11

Reimeus


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
like image 38
Elliott Frisch Avatar answered Nov 03 '22 05:11

Elliott Frisch