简体   繁体   English

Java从long值中删除毫秒精度

[英]Java remove millisecond precision from long value

so from this : 所以从这个:

1459245759880

to this 对此

1459245759000

Usual integer rounding? 通常的整数舍入?

long millis = 1459245759880L;
long rounded = millis / 1000 * 1000;

Using Java time (convenient if you need to do date/time operations on the result - in that case you can work with the instant): 使用Java时间(如果您需要对结果执行日期/时间操作,则很方便 - 在这种情况下,您可以使用该时刻):

Instant i = Instant.ofEpochMilli(millis).truncatedTo(ChronoUnit.SECONDS);
long rounded = i.toEpochMilli();

More convoluted (and probably not very clear): 更复杂(可能不是很清楚):

long rounded = 1000 * TimeUnit.SECONDS.convert(millis, TimeUnit.MILLISECONDS);
//OR
long rounded = TimeUnit.MILLISECONDS.convert(TimeUnit.SECONDS.convert(millis, TimeUnit.MILLISECONDS), TimeUnit.SECONDS);
 long x = 1459245759880;
 long y = x - (x % 1000);

Use simply the modulo operator to get reminder and then subtract it from the actual value. 使用模运算符来获取提醒,然后从实际值中减去它。

Why not this 为什么不呢

long value = 1459245759880L;
System.out.println(1000 * (value / 1000));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM