Convert java.util.Date to String

2018-12-31 08:25发布

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

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

16条回答
墨雨无痕
2楼-- · 2018-12-31 08:56

In Java, Convert a Date to a String using a format string:

// Create an instance of SimpleDateFormat used for formatting 
// the string representation of date (month/day/year)
DateFormat df = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");

// Get the date today 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 reportDate = df.format(today);

// Print what date is today!
System.out.println("Report Date: " + reportDate);

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

查看更多
宁负流年不负卿
3楼-- · 2018-12-31 08:56

Commons-lang DateFormatUtils is full of goodies (if you have commons-lang in your classpath)

//Formats a date/time into a specific pattern
 DateFormatUtils.format(yourDate, "yyyy-MM-dd HH:mm:SS");
查看更多
刘海飞了
4楼-- · 2018-12-31 08:57

Why don't you use Joda (org.joda.time.DateTime)? It's basically a one-liner.

Date currentDate = GregorianCalendar.getInstance().getTime();
String output = new DateTime( currentDate ).toString("yyyy-MM-dd HH:mm:ss");

// output: 2014-11-14 14:05:09
查看更多
旧时光的记忆
5楼-- · 2018-12-31 08:57

The easiest way to use it is as following:

currentISODate = new Date().parse("yyyy-MM-dd'T'HH:mm:ss", "2013-04-14T16:11:48.000");

where "yyyy-MM-dd'T'HH:mm:ss" is the format of the reading date

output: Sun Apr 14 16:11:48 EEST 2013

Notes: HH vs hh - HH refers to 24h time format - hh refers to 12h time format

查看更多
不流泪的眼
6楼-- · 2018-12-31 08:59
public static void main(String[] args) 
{
    Date d = new Date();
    SimpleDateFormat form = new SimpleDateFormat("dd-mm-yyyy hh:mm:ss");
    System.out.println(form.format(d));
    String str = form.format(d); // or if you want to save it in String str
    System.out.println(str); // and print after that
}
查看更多
还给你的自由
7楼-- · 2018-12-31 09:00

If you only need the time from the date, you can just use the feature of String.

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

This will automatically cut the time part of the String and save it inside the timeString.

查看更多
登录 后发表回答