436

我想将一个java.util.Date对象转换为StringJava 中的一个。

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

4

18 回答 18

812

使用方法将日期转换为字符串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

于 2011-04-16T01:04:40.983 回答
249
Format formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String s = formatter.format(date);
于 2011-04-16T01:02:29.003 回答
66

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

//Formats a date/time into a specific pattern
 DateFormatUtils.format(yourDate, "yyyy-MM-dd HH:mm:SS");
于 2013-01-25T05:04:15.437 回答
25
于 2016-10-02T00:57:10.893 回答
22

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

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

于 2015-06-25T17:41:20.057 回答
9

为什么不使用 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
于 2014-11-14T13:14:33.497 回答
7

看起来您正在寻找SimpleDateFormat

格式:yyyy-MM-dd kk:mm:ss

于 2011-04-16T01:01:54.040 回答
5

单发;)

获取日期

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

快乐编码:)

于 2018-02-03T20:43:11.133 回答
4
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;
}
于 2013-12-31T06:31:29.537 回答
4

如果您只需要日期中的时间,则可以使用 String 的功能。

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

这将自动剪切字符串的时间部分并将其保存在timeString.

于 2015-10-07T08:03:02.370 回答
4

以下是使用新的Java 8 Time API格式化legacy java.util.Date的示例:

    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss:SSS Z")
        .withZone(ZoneOffset.UTC);
    String utcFormatted = formatter.format(date.toInstant()); 

    ZonedDateTime utcDatetime = date.toInstant().atZone(ZoneOffset.UTC);
    String utcFormatted2 = utcDatetime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss:SSS Z"));
    // gives the same as above

    ZonedDateTime localDatetime = date.toInstant().atZone(ZoneId.systemDefault());
    String localFormatted = localDatetime.format(DateTimeFormatter.ISO_ZONED_DATE_TIME);
    // 2011-12-03T10:15:30+01:00[Europe/Paris]

    String nowFormatted = LocalDateTime.now().toString(); // 2007-12-03T10:15:30.123

很高兴DateTimeFormatter它可以被有效地缓存,因为它是线程安全的(不像SimpleDateFormat)。

预定义格式器列表和模式符号参考

学分:

如何使用 LocalDateTime 解析/格式化日期?(Java 8)

Java8 java.util.Date 转换为 java.time.ZonedDateTime

将 Instant 格式化为字符串

java 8 ZonedDateTime 和 OffsetDateTime 有什么区别?

于 2017-04-17T18:33:21.743 回答
3

最简单的使用方法如下:

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

其中“yyyy-MM-dd'T'HH:mm:ss”是读取日期的格式

输出:2013 年 4 月 14 日星期日 16:11:48 EEST

注:HH 与 hh - HH 指 24 小时制时间格式 - hh 指 12 小时制时间格式

于 2015-09-22T12:12:07.140 回答
2

试试这个,

import java.text.ParseException;
import java.text.SimpleDateFormat;

public class Date
{
    public static void main(String[] args) 
    {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String strDate = "2013-05-14 17:07:21";
        try
        {
           java.util.Date dt = sdf.parse(strDate);         
           System.out.println(sdf.format(dt));
        }
        catch (ParseException pe)
        {
            pe.printStackTrace();
        }
    }
}

输出:

2013-05-14 17:07:21

有关 java 中日期和时间格式的更多信息,请参阅下面的链接

Oracle 帮助中心

java中的日期时间示例

于 2017-11-06T11:38:52.953 回答
1
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
}
于 2015-03-25T21:11:08.073 回答
1

让我们试试这个

public static void main(String args[]) {

    Calendar cal = GregorianCalendar.getInstance();
    Date today = cal.getTime();
    DateFormat df7 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    try {           
        String str7 = df7.format(today);
        System.out.println("String in yyyy-MM-dd format is: " + str7);          
    } catch (Exception ex) {
      ex.printStackTrace();
    }
}

或效用函数

public String convertDateToString(Date date, String format) {
    String dateStr = null;
    DateFormat df = new SimpleDateFormat(format);

    try {
        dateStr = df.format(date);
    } catch (Exception ex) {
        ex.printStackTrace();
    }
    return dateStr;
}

Java 中将日期转换为字符串

于 2016-09-26T15:42:10.450 回答
1
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    String date = "2010-05-30 22:15:52";
    java.util.Date formatedDate = sdf.parse(date); // returns a String when it is parsed
    System.out.println(sdf.format(formatedDate)); // the use of format function returns a String
于 2018-07-23T14:52:16.837 回答
1

单线选项

这个选项很容易用一行来写实际的日期。

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

yourstringdate =  new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(Calendar.getInstance().getTime());
于 2019-05-22T22:20:37.330 回答
1
Date date = new Date();
String strDate = String.format("%tY-%<tm-%<td %<tH:%<tM:%<tS", date);
于 2019-07-26T15:48:21.497 回答