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

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


当前回答

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

其他回答

单线选项

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

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

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

看起来您正在寻找SimpleDateFormat。

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

Format formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String s = formatter.format(date);
    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

下面是使用新的Java 8 Time API格式化遗留的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

将即时格式化为字符串

java 8 ZonedDateTime和OffsetDateTime之间的区别是什么?