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

发布于 2024-11-01 20:52:12 字数 92 浏览 2 评论 0 原文

我想将 java.util.Date 对象转换为 Java 中的 String 。

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

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

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(18

鹿港巷口少年归 2024-11-08 20:52:12

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

Convert a Date to a String using DateFormat#format method:

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

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

罪歌 2024-11-08 20:52:12
Format formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String s = formatter.format(new java.util.Date());
Format formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String s = formatter.format(new java.util.Date());
下雨或天晴 2024-11-08 20:52:12

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

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

文档可以在这里找到: https://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/time/DateFormatUtils.html

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

Documentation can be found here: https://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/time/DateFormatUtils.html

捶死心动 2024-11-08 20:52:12

普通旧式 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);

这使用 格式化程序相对索引 而不是 SimpleDateFormat ,即 不是线程安全的,顺便说一句。

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

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-%<tm-%<td %<tH:%<tM:%<tS.%<tL%<tz", date);

String.format("The date and time in ISO format: %tF %<tT", date);

This uses Formatter and relative indexing instead of SimpleDateFormat which is not thread-safe, btw.

Slightly more repetitive but needs just one statement.
This may be handy in some cases.

娇纵 2024-11-08 20:52:12

太长了;博士

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 转换为 Instant即时 类代表 UTC 中时间轴上的时刻,分辨率为 纳秒(最多九 (9) 位小数)。

与 java.time 之间的转换是通过添加到旧类中的新方法来执行的。

Instant instant = myUtilDate.toInstant();

您的 java.util.Datejava.time.Instant 都在 UTC。如果您想查看 UTC 格式的日期和时间,那就这样吧。调用 toString 以标准 ISO 8601 格式生成字符串。

String output = instant.toString();  

2014-11-14T14:05:09Z

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

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

odt.toString(): 2020-05-01T21:25:35.957Z

查看代码在 IdeOne.com 上实时运行

要获取所需格式的字符串,请指定 DateTimeFormatter。您可以指定自定义格式。但我会使用预定义的格式化程序之一(ISO_LOCAL_DATE_TIME),并将其输出中的 T 替换为空格。

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

2014-11-14 14:05:09

顺便说一句,我不推荐这种故意丢失 与 UTC 的偏移量或时区信息。造成该字符串的日期时间值的含义含糊不清。

还要注意数据丢失,因为在日期时间值的字符串表示中,任何小数秒都会被忽略(有效地截断)。

要通过某个特定区域的挂钟时间查看同一时刻,请应用ZoneId 来获取 ZonedDateTime

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

zdt.toString(): 2014-11-14T14:05:09-05:00[美国/蒙特利尔]

要生成格式化字符串,请执行与上面相同的操作,但将 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.

通过传递实例来应用该格式化程序。

String output = zdt.format( f );

关于 java.time

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

Joda-Time 项目,现已在 维护模式,建议迁移到 java.time。

要了解更多信息,请参阅 Oracle 教程。并在 Stack Overflow 上搜索许多示例和解释。

许多 java.time 功能都向后移植到 Java 6 和 Java 6。 ThreeTen-Backport 中的 7 并进一步适应 AndroidThreeTenABP(请参阅如何使用...)。

ThreeTen-Extra 项目通过附加类扩展了 java.time。该项目是 java.time 未来可能添加的内容的试验场。

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

The modern way is with the java.time classes that now supplant the troublesome old legacy date-time classes.

First convert your java.util.Date to an Instant. The Instant class represents a moment on the timeline in UTC with a resolution of nanoseconds (up to nine (9) digits of a decimal fraction).

Conversions to/from java.time are performed by new methods added to the old classes.

Instant instant = myUtilDate.toInstant();

Both your java.util.Date and java.time.Instant are in UTC. If you want to see the date and time as UTC, so be it. Call toString to generate a String in standard ISO 8601 format.

String output = instant.toString();  

2014-11-14T14:05:09Z

For other formats, you need to transform your Instant into the more flexible OffsetDateTime.

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

odt.toString(): 2020-05-01T21:25:35.957Z

See that code run live at IdeOne.com.

To get a String in your desired format, specify a DateTimeFormatter. You could specify a custom format. But I would use one of the predefined formatters (ISO_LOCAL_DATE_TIME), and replace the T in its output with a SPACE.

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

2014-11-14 14:05:09

By the way I do not recommend this kind of format where you purposely lose the offset-from-UTC or time zone information. Creates ambiguity as to the meaning of that string’s date-time value.

Also beware of data loss, as any fractional second is being ignored (effectively truncated) in your String’s representation of the date-time value.

To see that same moment through the lens of some particular region’s wall-clock time, apply a ZoneId to get a ZonedDateTime.

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

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

To generate a formatted String, do the same as above but replace odt with zdt.

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

2014-11-14 14:05:09

If executing this code a very large number of times, you may want to be a bit more efficient and avoid the call to String::replace. Dropping that call also makes your code shorter. If so desired, specify your own formatting pattern in your own DateTimeFormatter object. Cache this instance as a constant or member for reuse.

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

Apply that formatter by passing the instance.

String output = zdt.format( f );

About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old date-time classes such as java.util.Date, .Calendar, & java.text.SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to java.time.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations.

Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport and further adapted to Android in ThreeTenABP (see How to use…).

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time.

冷了相思 2024-11-08 20:52:12

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

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
好倦 2024-11-08 20:52:12

您似乎正在寻找 SimpleDateFormat

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

It looks like you are looking for SimpleDateFormat.

Format: yyyy-MM-dd kk:mm:ss

宁愿没拥抱 2024-11-08 20:52:12

单次;)

获取日期

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

快乐编码:)

In single shot ;)

To get the Date

String date = new SimpleDateFormat("yyyy-MM-dd",   Locale.getDefault()).format(new Date());

To get the Time

String time = new SimpleDateFormat("hh:mm", Locale.getDefault()).format(new Date());

To get the date and time

String dateTime = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss", Locale.getDefaut()).format(new Date());

Happy coding :)

月朦胧 2024-11-08 20:52:12
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;
}
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;
}
浮世清欢 2024-11-08 20:52:12

以下是使用新的 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 不同)。

预定义格式和模式表示法参考列表< /a>.

学分:

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

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

将 Instant 格式化为String

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

Here are examples of using new Java 8 Time API to format 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

It is nice about DateTimeFormatter that it can be efficiently cached as it is thread-safe (unlike SimpleDateFormat).

List of predefined fomatters and pattern notation reference.

Credits:

How to parse/format dates with LocalDateTime? (Java 8)

Java8 java.util.Date conversion to java.time.ZonedDateTime

Format Instant to String

What's the difference between java 8 ZonedDateTime and OffsetDateTime?

高冷爸爸 2024-11-08 20:52:12

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

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

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

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.

习惯那些不曾习惯的习惯 2024-11-08 20:52:12

最简单的使用方法如下:

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

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

:Sun Apr 14 16:11:48 EEST 2013

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

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

半﹌身腐败 2024-11-08 20:52:12
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
}
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
}
将军与妓 2024-11-08 20:52:12

让我们试试这个

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;
}

来自 Convert Java 中的日期转字符串

Let's try this

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

Or a utility function

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;
}

From Convert Date to String in Java

铜锣湾横着走 2024-11-08 20:52:12
    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
    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
春花秋月 2024-11-08 20:52:12
Date date = new Date();
String strDate = String.format("%tY-%<tm-%<td %<tH:%<tM:%<tS", date);
Date date = new Date();
String strDate = String.format("%tY-%<tm-%<td %<tH:%<tM:%<tS", date);
柳若烟 2024-11-08 20:52:12

一行选项

此选项可以使用简单的一行来写入实际日期。

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

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

One Line option

This option gets a easy one-line to write the actual date.

Please, note that this is using Calendar.class and SimpleDateFormat, and then it's not
logical to use it under Java8.

yourstringdate =  new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(Calendar.getInstance().getTime());
永不分离 2024-11-08 20:52:12

如果您想在结果字符串中包含时区信息:

public String getFormattedDate(Date date) {
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX");
    sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
    return sdf.format(date);
}

If you want to include timezone information in the resultant string:

public String getFormattedDate(Date date) {
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX");
    sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
    return sdf.format(date);
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文