问题
Since the java.util.Date
object 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.
I checked a question related to my question...
How to remove sub seconds part of Date object
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 0
from my Date format???
回答1:
Basic answer is, you can't. The value returned by Date#toString
is a representation of the Date
object and it carries no concept of format other then what it uses internally for the toString
method.
Generally this shouldn't be used for display purpose (except for rare occasions)
Instead you should be using some kind of 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 ;)
回答2:
tl;dr
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
.
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.
Instant
Convert your old java.util.Date
object to a java.time.Instant
by calling new method added to the old class.
Instant instant = myJavaUtilDate.toInstant() ;
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.
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.
Convert Instant
to a OffsetDateTime
for more flexible formatting.
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 Date
and Instant
are 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 ZoneId
and ZonedDateTime
class names for much more info.
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.*
classes.
Where to obtain the java.time classes?
- Java SE 8, Java SE 9, Java SE 10, and later
- Built-in.
- Part of the standard Java API with a bundled implementation.
- Java 9 adds some minor features and fixes.
- Java SE 6 and Java SE 7
- Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
- Android
- Later versions of Android bundle implementations of the java.time classes.
- For earlier Android (<26), the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….
The ThreeTen-Extra project 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.
回答3:
You can use SimpleDateFormatter
. Please see the following code.
SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss a");
Date now = date.getTime();
System.out.println(formatter.format(now));
回答4:
Use Apache's DateUtils:
import org.apache.commons.lang.time.DateUtils;
...
DateUtils.truncate(new Date(), Calendar.SECOND)
回答5:
You can use the SimpleDateFormat
class to format the date as necessary. Due to the diversity of possible combinations, I will simply include the documentation link here:
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));
回答6:
Just for the record, the accepted answer given at the post you linked works:
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));
}
回答7:
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;
}
回答8:
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));
来源:https://stackoverflow.com/questions/21448500/how-to-remove-milliseconds-from-date-object-format-in-java