业务场景中,不乏会需要取到当前系统的时间,做一些判断,比如判断某个执行过程需要花多长时间,然后将时间记录下来,返回给业务查看;或者需要或者一个唯一的值做一些表单单号,那么当前系统时间就是唯一的,可以适用,等等。那下面总结下有哪几种方式来获取。
一、System类中currentTimeMillis()方法
方法功能:返回从1970年1月1日午夜(UTC)开始到当前时间的毫秒值. 返回类型为 long ,表示毫秒为单位的当前时间。
特别注意:如果是想获取时间戳,推荐用System.currentTimeMillis(),获取时间戳效率最高,Date类也可以获取时间戳,效率较低。
@Test
public void test(){
long l = System.currentTimeMillis(); //获取时间戳效率最高
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String format = dateFormat.format(l);
System.out.println(l); //1663989713565
System.out.println(format);//2022-09-24
}