java 如何删除Date对象的亚秒部分
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3634771/
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
How to remove sub seconds part of Date object
提问by user339108
java.util.Date gets stored as 2010-09-03 15:33:22.246 when the SQL data type is timestamp, how do I set the sub seconds to zero (e.g. 246 in this case) prior to storing the record.
java.util.Date 被存储为 2010-09-03 15:33:22.246 当 SQL 数据类型是时间戳时,如何在存储记录之前将子秒设置为零(例如在这种情况下为 246)。
回答by Jon Skeet
The simplest way would be something like:
最简单的方法是这样的:
long time = date.getTime();
date.setTime((time / 1000) * 1000);
In other words, clear out the last three digits of the "millis since 1970 UTC".
换句话说,清除“自 1970 UTC 以来的毫秒”的最后三位数字。
I believe that will alsoclear the nanoseconds part if it's a java.sql.Timestamp
.
我相信,这将也清除纳秒的一部分,如果它是一个java.sql.Timestamp
。
回答by Erkan Haspulat
Here is an idea:
这是一个想法:
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 Daniel De León
java.util.Calendar
can help you.
java.util.Calendar
能帮你。
Calendar instance = Calendar.getInstance();
instance.setTime(date);
instance.clear(Calendar.SECOND);
date = instance.getTime();
回答by Steve Park
Here is another way by java 8 Instant api
这是java 8 Instant api的另一种方式
LocalDateTime now = LocalDateTime.now();
Instant instant = now.atZone(ZoneId.systemDefault()).toInstant().truncatedTo(ChronoUnit.SECONDS);
Date date = Date.from(instant);
or
或者
Date now = new Date();
Instant instant = now.toInstant().truncatedTo(ChronoUnit.SECONDS);
Date date = Date.from(instant);
回答by br2000
Alternatively, you can use Apache Commons DateUtils, for example:
或者,您可以使用 Apache Commons DateUtils,例如:
DateUtils.setMilliseconds(new Date(), 0);