在Java中,时间戳(timestamp)通常指的是自1970年1月1日(UTC)以来的毫秒数。如果你想去除这个时间戳中的毫秒部分,即只保留到秒,你可以通过将时间戳除以1000并向下取整来实现。这里有几种不同的方式来完成这个操作。

方法1:使用Math.floorDiv()(Java 9及以上)

从Java 9开始,Math类引入了floorDiv()方法,这个方法可以执行向下取整的除法。但是,由于时间戳已经是整数,直接使用/进行除法操作就足够了,因为整数除法默认就是向下取整的。不过,为了说明Math.floorDiv()的用法,这里还是展示一下(虽然在这个特定场景下可能不那么必要):

 long timestamp = System.currentTimeMillis(); // 获取当前时间戳  
 
 long timestampInSeconds = Math.floorDiv(timestamp, 1000); // 实际在这个场景下等同于timestamp / 1000
  • 1.
  • 2.
  • 3.

方法2:直接使用除法

对于大多数情况,直接使用/进行除法就足够了,因为Java中的整数除法会自动向下取整:

 long timestamp = System.currentTimeMillis(); // 获取当前时间戳  
 
 long timestampInSeconds = timestamp / 1000; // 直接除以1000,得到秒级时间戳
  • 1.
  • 2.
  • 3.

方法3:使用InstantDuration(Java 8及以上)

如果你使用的是Java 8或更高版本,并且想要更面向对象的方式来处理时间,你可以使用InstantDuration类。虽然这可能会比直接操作时间戳更复杂一些,但它提供了更好的可读性和灵活性:

 import java.time.Instant;  

 public class Main {  
 
     public static void main(String[] args) {  
 
         Instant instant = Instant.now(); // 获取当前时间  
 
         long timestamp = instant.toEpochMilli(); // 转换为毫秒级时间戳  
 
         long timestampInSeconds = instant.getEpochSecond(); // 直接获取秒级时间戳  
 
   
 
         System.out.println("Millisecond timestamp: " + timestamp);  
 
         System.out.println("Second timestamp: " + timestampInSeconds);  
 
     }  
 
 }
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.

在这个例子中,Instant.now()获取了当前的Instant对象,它代表了一个时间戳。然后,你可以使用toEpochMilli()方法将其转换为毫秒级的时间戳,或者使用getEpochSecond()方法直接获取秒级的时间戳。

总之,去除时间戳中的毫秒部分通常是通过将其除以1000并向下取整来实现的。在Java中,这可以通过简单的除法操作或者利用Java 8及以上版本中引入的新时间日期API来完成。