我想将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);

其他回答

public static String formateDate(String dateString) {
    Date date;
    String formattedDate = "";
    try {
        date = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss",Locale.getDefault()).parse(dateString);
        formattedDate = new SimpleDateFormat("dd/MM/yyyy",Locale.getDefault()).format(date);
    } catch (ParseException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    return formattedDate;
}

为什么不用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

单镜头;)

获取日期

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());

快乐编码:)

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

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

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

在普通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不是线程安全的,顺便说一句。

稍微重复一点,但只需要一个陈述。 这在某些情况下可能很方便。