print current date in java

后端 未结 9 1775
半阙折子戏
半阙折子戏 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:25
    public static void main(String[] args) {
    
        DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
        //get current date time with Date()
        Date date = new Date();
        System.out.println(dateFormat.format(date));
    
        //get current date time with Calendar()
        Calendar cal = Calendar.getInstance();
        System.out.println(dateFormat.format(cal.getTime()));
    
    }
    
    0 讨论(0)
  • 2020-12-18 20:31

    You should not use the toString() method, because:

    The toString method for class Object returns a string consisting of the name of the class of which the object is an instance, the at-sign character `@', and the unsigned hexadecimal representation of the hash code of the object. In other words, this method returns a string equal to the value of:

    getClass().getName() + '@' + Integer.toHexString(hashCode())

    Quote from docs.oracle: http://docs.oracle.com/javase/7/docs/api/java/lang/Object.html).

    The Date class is designed to use like everyone else has answered. Just wanted to explain/give you a reference to why.

    0 讨论(0)
  • 2020-12-18 20:32
    import java.util.Date;
    public class Dte {
    
        public static void main(String[] args) {
            Date date = new Date();
            System.out.println(date.toString());
        }
    }
    

    Change the class name Date to Dte or some thing and the code will work properly.

    The output is : Mon Nov 03 21:27:15 IST 2014

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