print current date in java

后端 未结 9 1774
半阙折子戏
半阙折子戏 2020-12-18 19:38

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          


        
相关标签:
9条回答
  • 2020-12-18 20:13

    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
    
    0 讨论(0)
  • 2020-12-18 20:14

    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

    0 讨论(0)
  • 2020-12-18 20:15

    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

    0 讨论(0)
  • 2020-12-18 20:19

    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/

    0 讨论(0)
  • 2020-12-18 20:21

    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
    
    0 讨论(0)
  • 2020-12-18 20:25

    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

    0 讨论(0)
提交回复
热议问题