如何从 Java 中的日期对象格式中删除毫秒

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21448500/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 08:47:07  来源:igfitidea点击:

How to remove milliseconds from Date Object format in Java

javajava.util.date

提问by Ankit Lamba

Since the java.util.Dateobject stores Date as 2014-01-24 17:33:47.214, but I want the Date format as 2014-01-24 17:33:47. I want to remove the milliseconds part.

由于java.util.Date对象将 Date 存储为2014-01-24 17:33:47.214,但我希望 Date 格式为2014-01-24 17:33:47. 我想删除毫秒部分。

I checked a question related to my question...

我检查了一个与我的问题相关的问题...

How to remove sub seconds part of Date object

如何删除Date对象的亚秒部分

I've tried the given answer

我已经尝试了给定的答案

long time = date.getTime();
date.setTime((time / 1000) * 1000);

but I've got my result Date format as 2014-01-24 17:33:47.0. How can I remove that 0from my Date format???

但我的结果日期格式为2014-01-24 17:33:47.0. 如何0从我的日期格式中删除它???

采纳答案by MadProgrammer

Basic answer is, you can't. The value returned by Date#toStringis a representation of the Dateobject and it carries no concept of format other then what it uses internally for the toStringmethod.

基本答案是,你不能。返回的值Date#toStringDate对象的表示,除了它内部用于toString方法的格式之外,它不包含任何格式概念。

Generally this shouldn't be used for display purpose (except for rare occasions)

通常这不应该用于显示目的(极少数情况除外)

Instead you should be using some kind of DateFormat

相反,您应该使用某种 DateFormat

For example...

例如...

Date date = new Date();
System.out.println(date);
System.out.println(DateFormat.getDateTimeInstance().format(date));
System.out.println(DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT).format(date));
System.out.println(DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.MEDIUM).format(date));
System.out.println(DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG).format(date));

Will output something like...

会输出类似...

Thu Jan 30 16:29:31 EST 2014
30/01/2014 4:29:31 PM
30/01/14 4:29 PM
30/01/2014 4:29:31 PM
30 January 2014 4:29:31 PM

If you get really stuck, you can customise it further by using a SimpleDateFormat, but I would avoid this if you can, as not everybody uses the same date/time formatting ;)

如果你真的被卡住了,你可以使用 a 进一步自定义它SimpleDateFormat,但如果可以的话我会避免这种情况,因为不是每个人都使用相同的日期/时间格式;)

回答by Mayur

You can use SimpleDateFormatter. Please see the following code.

您可以使用SimpleDateFormatter. 请看下面的代码。

SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss a");
Date now = date.getTime();
System.out.println(formatter.format(now));

回答by John Bergman

You can use the SimpleDateFormatclass to format the date as necessary. Due to the diversity of possible combinations, I will simply include the documentation link here:

您可以SimpleDateFormat根据需要使用该类来格式化日期。由于可能组合的多样性,我将在这里简单地包含文档链接:

http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html

http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html

Your code will look something similar to the following:

您的代码将类似于以下内容:

System.out.println(new SimpleDateFormat("MM/dd/yyyy").format(date));

回答by Nick Grealy

Please try the following date formatter:

请尝试以下日期格式化程序:

import java.text.*;
SimpleDateFormat tmp = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
System.out.println(tmp.format(date));

回答by Basil Bourque

tl;dr

tl;博士

Lop off the fractional second.

关闭小数秒。

myJavaUtilDate.toInstant()                         // Convert from legacy class to modern class. Returns a `Instant` object.
              .truncatedTo( ChronoUnit.SECONDS )   // Generate new `Instant` object based on the values of the original, but chopping off the fraction-of-second.

Hide the fractional second, when generating a String.

生成String.

myJavaUtilDate.toInstant()                         // Convert from legacy class to modern class. Returns a `Instant` object.
              .atOffset( ZoneOffset.UTC )          // Return a `OffsetDateTime` object. 
              .format( DateTimeFormatter.ofPattern( "uuuu-MM-dd HH:mm:ss" ) ). // Ask the `OffsetDateTime` object to generate a `String` with text representing its value, in a format defined in the `DateTimeFormatter` object.

Avoid legacy date-time classes

避免遗留的日期时间类

You are using troublesome old date-time classes, now legacy, supplanted by the java.time classes.

您正在使用麻烦的旧日期时间类,现在是遗留的,被 java.time 类取代。

Instant

Instant

Convert your old java.util.Dateobject to a java.time.Instantby calling new method added to the old class.

通过调用添加到旧类的新方法将旧java.util.Date对象转换为 a java.time.Instant

Instant instant = myJavaUtilDate.toInstant() ;

Table of types of date-time classes in modern java.time versus legacy.

现代 java.time 与旧版中日期时间类的类型表。

Truncate

截短

If you want to change value of the data itself to drop the fraction of a second, you can truncate. The java.time classes use immutable objects, so we generate a new object rather than alter (mutate) the original.

如果您想更改数据本身的值以减少几分之一秒,您可以截断。java.time 类使用不可变对象,因此我们生成一个新对象而不是改变(变异)原始对象。

Instant instantTruncated = instant.truncatedTo( ChronoUnit.SECONDS );

Generating string

生成字符串

If instead of truncating you merely want to suppress the display of the fractional seconds when generating a string representing the date-time value, define a formatter to suit your needs.

如果在生成表示日期时间值的字符串时不想截断您只想抑制小数秒的显示,请定义一个格式化程序以满足您的需要。

For example, "uuuu-MM-dd HH:mm:ss" makes no mention of a fractional second, so any milliseconds contained in the data simply does not appear in the generated string.

例如,“uuuu-MM-dd HH:mm:ss”没有提到小数秒,因此数据中包含的任何毫秒都不会出现在生成的字符串中。

Convert Instantto a OffsetDateTimefor more flexible formatting.

转换InstantOffsetDateTime更灵活的格式。

DateTimeFormatter f = DateTimeFormatter.ofPattern( "uuuu-MM-dd HH:mm:ss" );
OffsetDateTime odt = instant.atOffset( ZoneOffset.UTC )
String output = odt.format( f );

Time zone

时区

Note that your Question ignores the issue of time zone. If you intended to use UTC, the above code works as both Dateand Instantare in UTC by definition. If instead you want to perceive the given data through the lens of some region's wall-clock time, apply a time zone. Search Stack Overflow for ZoneIdand ZonedDateTimeclass names for much more info.

请注意,您的问题忽略了时区问题。如果您打算使用 UTC,上面的代码既可以使用,DateInstant可以根据定义使用 UTC 。相反,如果您想通过某个地区的挂钟时间来感知给定的数据,请应用时区。搜索 Stack OverflowZoneIdZonedDateTime类名以获取更多信息。



About java.time

关于java.time

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

java.time框架是建立在Java 8和更高版本。这些类取代了麻烦的旧的遗留日期时间类,例如java.util.Date, Calendar, & SimpleDateFormat

The Joda-Timeproject, now in maintenance mode, advises migration to the java.timeclasses.

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

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

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

You may exchange java.timeobjects directly with your database. Use a JDBC drivercompliant with JDBC 4.2or later. No need for strings, no need for java.sql.*classes.

您可以直接与您的数据库交换java.time对象。使用符合JDBC 4.2或更高版本的JDBC 驱动程序。不需要字符串,不需要类。java.sql.*

Where to obtain the java.time classes?

从哪里获得 java.time 类?

The ThreeTen-Extraproject extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

ThreeTen-额外项目与其他类扩展java.time。该项目是未来可能添加到 java.time 的试验场。你可能在这里找到一些有用的类,比如IntervalYearWeekYearQuarter,和更多

回答by Bernat

Just for the record, the accepted answer given at the post you linkedworks:

仅作记录,您链接帖子中给出的已接受答案有效:

public static void main(String[] args) {
       SimpleDateFormat df = new SimpleDateFormat("S");
       Date d = new Date();
       System.out.println(df.format(d));
       Calendar c = Calendar.getInstance();
       c.set(Calendar.MILLISECOND, 0);
       d.setTime(c.getTimeInMillis());
       System.out.println(df.format(d));

}

回答by Scott White

Use Apache's DateUtils:

使用 Apache 的 DateUtils:

import org.apache.commons.lang.time.DateUtils;
...
DateUtils.truncate(new Date(), Calendar.SECOND)

回答by gene b.

Truncate to Seconds (no milliseconds), return a new Date:

截断到秒(无毫秒),返回一个新的日期:

public Date truncToSec(Date date) {
    Calendar c = Calendar.getInstance();
    c.setTime(date);
    c.set(Calendar.MILLISECOND, 0);
    Date newDate = c.getTime();
    return newDate;
}