Convert java.util.Date to String

前端 未结 18 2331
悲&欢浪女
悲&欢浪女 2020-11-22 05:37

I want to convert a java.util.Date object to a String in Java.

The format is 2010-05-30 22:15:52

18条回答
  •  无人及你
    2020-11-22 05:52

    Let's try this

    public static void main(String args[]) {
    
        Calendar cal = GregorianCalendar.getInstance();
        Date today = cal.getTime();
        DateFormat df7 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    
        try {           
            String str7 = df7.format(today);
            System.out.println("String in yyyy-MM-dd format is: " + str7);          
        } catch (Exception ex) {
          ex.printStackTrace();
        }
    }
    

    Or a utility function

    public String convertDateToString(Date date, String format) {
        String dateStr = null;
        DateFormat df = new SimpleDateFormat(format);
    
        try {
            dateStr = df.format(date);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return dateStr;
    }
    

    From Convert Date to String in Java

提交回复
热议问题