我想将Java. util. date对象转换为Java中的字符串。
格式为2010-05-30 22:15:52
我想将Java. util. date对象转换为Java中的字符串。
格式为2010-05-30 22:15:52
当前回答
在普通java中可选的一行程序:
String.format("The date: %tY-%tm-%td", date, date, date);
String.format("The date: %1$tY-%1$tm-%1$td", date);
String.format("Time with tz: %tY-%<tm-%<td %<tH:%<tM:%<tS.%<tL%<tz", date);
String.format("The date and time in ISO format: %tF %<tT", date);
这使用Formatter和相对索引,而不是SimpleDateFormat不是线程安全的,顺便说一句。
稍微重复一点,但只需要一个陈述。 这在某些情况下可能很方便。
其他回答
看起来您正在寻找SimpleDateFormat。
格式:yyyy-MM-dd kk:mm:ss
Format formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String s = formatter.format(date);
单线选项
该选项通过简单的一行来编写实际的日期。
请注意,这是使用Calendar.class和SimpleDateFormat,然后它不是 在Java8下使用它是合乎逻辑的。
yourstringdate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(Calendar.getInstance().getTime());
使用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
为什么不用Joda (org.joda.time.DateTime)? 基本上就是一行代码。
Date currentDate = GregorianCalendar.getInstance().getTime();
String output = new DateTime( currentDate ).toString("yyyy-MM-dd HH:mm:ss");
// output: 2014-11-14 14:05:09