将java.util.Date转换为字符串

我想在Java中把java.util.Date对象转换为String

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

对该问题的评论 (4)
解决办法

使用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

评论(8)
Format formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String s = formatter.format(date);
评论(1)

Commons-lang DateFormatUtils充满了好东西(如果你的classpath里有commons-lang的话)。

//Formats a date/time into a specific pattern
 DateFormatUtils.format(yourDate, "yyyy-MM-dd HH:mm:SS");
评论(0)

tl;dr

myUtilDate.toInstant()  // Convert `java.util.Date` to `Instant`.
          .atOffset( ZoneOffset.UTC )  // Transform `Instant` to `OffsetDateTime`.
          .format( DateTimeFormatter.ISO_LOCAL_DATE_TIME )  // Generate a String.
          .replace( "T" , " " )  // Put a SPACE in the middle.

2014-11-14 14:05:09

java.time

现代的方法是使用java.time类,它现在取代了麻烦的旧日期-时间类。

首先将你的java.util.Date转换为InstantInstant](http://docs.oracle.com/javase/8/docs/api/java/time/Instant.html)类以[UTC](https://en.wikipedia.org/wiki/Coordinated_Universal_Time)表示时间轴上的一个时刻,其分辨率为[纳秒](https://en.wikipedia.org/wiki/Nanosecond)(最多为小数点后的九(9)位)。

java.time与java.time之间的转换由添加到旧类中的新方法来完成。

Instant instant = myUtilDate.toInstant();

你的java.util.Datejava.time.Instant都是以UTC为单位。 如果你想把日期和时间看成UTC,那就这样吧。 调用toString生成一个标准[ISO 8601][2]格式的字符串。

String output = instant.toString();  

2014-11-14T14:05:09Z

对于其他格式,您需要将Instant转换为更灵活的[OffsetDateTime][3]。

OffsetDateTime odt = instant.atOffset( ZoneOffset.UTC );

odt.toString()。 2014-11-14T14:05:09+00:00

要想得到一个你所需格式的字符串,请指定一个[DateTimeFormatter][4]。 你可以指定一个自定义的格式。 但我会使用一个预定义的格式([ISO_LOCAL_DATE_TIME][5]),并在其输出中用空格代替T

String output = odt.format( DateTimeFormatter.ISO_LOCAL_DATE_TIME )
                   .replace( "T" , " " );

2014-11-14 14:05:09

对了,我不推荐这种故意丢失[offset-from-UTC][6]或时区信息的格式。 对该字符串的日期-时间值的含义产生歧义。

同时也要小心数据丢失,因为在你的String的日期-时间值表示中,任何小数点的秒都会被忽略(有效地截断)。

如果要通过某个特定区域的[挂钟时间][7]来查看同一时刻,可以应用一个ZoneId来获得一个ZonedDateTime

ZoneId z = ZoneId.of( "America/Montreal" );
ZonedDateTime zdt = instant.atZone( z );

zdt.toString()。 2014-11-14T14:05:09-05:00[America/Montreal]

要生成一个格式化的字符串,请执行与上述相同的操作,但将 "odt "替换为 "zdt"。

String output = zdt.format( DateTimeFormatter.ISO_LOCAL_DATE_TIME )
                   .replace( "T" , " " );

2014-11-14 14:05:09

如果执行这段代码的次数非常多,你可能想提高效率,避免调用String::replace。 丢掉这个调用也会让你的代码更短。 如果需要,可以在自己的DateTimeFormatter对象中指定自己的格式化模式。 将这个实例缓存为一个常量或成员,以便重用。

DateTimeFormatter f = DateTimeFormatter.ofPattern( "uuuu-MM-dd HH:mm:ss" );  // Data-loss: Dropping any fractional second.

通过传递实例来应用该formatter。

String output = zdt.format( f );

关于java.time

java.time框架内置于Java 8及更新版本中。 这些类取代了麻烦的旧的日期-时间类,如java.util.Date.Calendar、& java.text.SimpleDateFormat

Joda-Time](http://www.joda.org/joda-time/)项目,现在处于[维护模式](https://en.wikipedia.org/wiki/Maintenance_mode),建议迁移到java.time

要了解更多,请看Oracle教程。 并在Stack Overflow中搜索许多例子和解释。

java.time的大部分功能都回移植到了Java 6 &amp.7中。 7的ThreeTen-Backport,并在ThreeTenABP中进一步适配到Android(参见如何使用...)。

ThreeTen-Extra](http://www.threeten.org/threeten-extra/)项目扩展了java.time的附加类。 这个项目是对java.time未来可能增加的类的一个试验场。

1:

[2]: https://en.wikipedia.org/wiki/ISO_8601 [3]: http://docs.oracle.com/javase/8/docs/api/java/time/OffsetDateTime.html [4]: http://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html [5]: https://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html#ISO_LOCAL_DATE_TIME [6]: https://en.wikipedia.org/wiki/UTC_offset [7]: https://en.wikipedia.org/wiki/Wall-clock_time

评论(1)

Altenative one-liners in plain-old 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-%
评论(0)

为什么不使用 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
评论(1)

看起来你在寻找SimpleDateFormat

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

评论(6)

在一次拍摄中;)

获取日期

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

编码快乐:)

评论(1)

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

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

这将自动剪掉字符串的时间部分,并将其保存在timeString内。

评论(1)
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;
}
评论(0)

最简单的使用方法如下。

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

其中"yyy-MM-dd'T'HH:mm:ss" 是阅读日期的格式

输出。 Sun Apr 14 16:11:48 EEST 2013年4月14日

注:HH与hh

  • HH是指24小时时间格式
  • hh指的是12h时间格式。
评论(1)

下面是使用新的[Java 8 Time API][1]来格式化[legacy][2]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)。

[预定义fomatters列表和模式符号参考][3]。

信用。

https://stackoverflow.com/questions/22463062/how-to-parse-format-dates-with-localdatetime-java-8

https://stackoverflow.com/questions/25376242/java8-java-util-date-conversion-to-java-time-zoneddatetime

https://stackoverflow.com/questions/25229124/format-instant-to-string

https://stackoverflow.com/questions/30234594/whats-the-difference-between-java-8-zoneddatetime-and-offsetdatetime

[1]: http://www.oracle.com/technetwork/articles/java/jf14-date-time-2125367.html [2]: https://docs.oracle.com/javase/tutorial/datetime/iso/legacy.html [3]: [3]:https://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html#predefined

评论(0)

试试这个

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帮助中心][1]

[java中的日期时间示例][2]

[1]: https://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html [2]: https://www.flowerbrackets.com/java-date-to-string/

评论(0)

Date date = new Date();
String strDate = String.format("%tY-%
评论(0)
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
}
评论(0)
    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
评论(0)

试试这个

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中转换日期为字符串][1]

[1]: http://javabycode.com/java-core/java-common/convert-date-to-string-in-java.html

评论(0)

单行选择

这个选项得到了一个简单的单行来写实际日期。

请注意,这是用Calendar.classSimpleDateFormat,然后它不是 &gt。 在Java8下使用它是符合逻辑的。

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