我想将Java. util. date对象转换为Java中的字符串。

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


当前回答

Date date = new Date();
String strDate = String.format("%tY-%<tm-%<td %<tH:%<tM:%<tS", date);

其他回答

如果只需要从日期到时间,则可以使用String的特性。

Date test = new Date();
String dayString = test.toString();
String timeString = dayString.substring( 11 , 19 );

这将自动切断字符串的时间部分,并将其保存在timeString中。

单线选项

该选项通过简单的一行来编写实际的日期。

请注意,这是使用Calendar.class和SimpleDateFormat,然后它不是 在Java8下使用它是合乎逻辑的。

yourstringdate =  new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(Calendar.getInstance().getTime());

单镜头;)

获取日期

String date = new SimpleDateFormat("yyyy-MM-dd",   Locale.getDefault()).format(new Date());

为了得到时间

String time = new SimpleDateFormat("hh:mm", Locale.getDefault()).format(new Date());

来获取日期和时间

String dateTime = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss", Locale.getDefaut()).format(new Date());

快乐编码:)

使用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

common -lang DateFormatUtils充满了好东西(如果你的类路径中有common -lang)

//Formats a date/time into a specific pattern
 DateFormatUtils.format(yourDate, "yyyy-MM-dd HH:mm:SS");