将 java.util.Date 转换为字符串

2022-08-31 04:32:30

我想在Java中将对象转换为a。java.util.DateString

格式为2010-05-30 22:15:52


答案 1

使用 DateFormat#format 方法将日期转换为字符串

String pattern = "MM/dd/yyyy HH:mm:ss";

// Create an instance of SimpleDateFormat used for formatting 
// the string representation of date according to the chosen pattern
DateFormat df = new SimpleDateFormat(pattern);

// Get the today date using Calendar object.
Date today = Calendar.getInstance().getTime();        
// Using DateFormat format method we can create a string 
// representation of a date with the defined format.
String todayAsString = df.format(today);

// Print the result!
System.out.println("Today is: " + todayAsString);

http://www.kodejava.org/examples/86.html


答案 2
Format formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String s = formatter.format(date);