首先获取当前时间:
java.util.Date nowdate = new java.util.Date()
2/2
然后如果你想时间的格式和你想用的时间格式一致 那么就要格式化时间了SimpleDateFormat 的包在java.text包下SimpleDateFormat
sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss") //年月日 时分秒
String t = sdf.parse(nowdate);
一、获取毫秒数的代码:
(1)System.currentTimeMillis() 这种方式速度最快。
(2)Calendar.getInstance().getTimeInMillis() 这种方式速度最慢。
二、获取微秒数的代码:
微秒使用System.nanoTime()方法:如果Java程序需要高精度的计时,如1毫秒或者更小,使用System.nanoTime()方法,可以满足需求。
扩展资料:
获取微秒函数System.nanoTime() 的隐患:
System.currentTimeMillis() 起始时间是基于 1970.1.1 0:00:00 这个确定的时间的,而System.nanoTime()是基于cpu核心的时钟周期来计时,它的开始时间是不确定的。
但是在多核处理器上,由于每个核心的开始时间不确定,那么
“long start = System.nanoTime()String ip = Utilities.getIpByUrl(url)long cost = System.nanoTime() - start ”
这段代码有可能会运行在两个不同的cpu核心上,从而导致得到的结果完全不符逻辑。