一、new Date().getTime() 和 System.currentTimeMillis()区别
new Date().getTime()
和 System.currentTimeMillis()
都可以用来获取当前时间的时间戳,但是它们的用法和返回值略有不同。
new Date().getTime()
返回一个表示当前日期和时间的 Date
对象,但是它不能改变日期和时间,只能用于获取当前时间。
System.currentTimeMillis()
返回一个表示当前时间的 long
值,精度高于 new Date().getTime()
,可以用于获取当前时间,并且可以用于对日期和时间进行修改。
1. 平时一般我们获取时间戳有这种写法
String nowTime = sdf.format(new Date().getTime());
2. 也有这种写法的 建议大家! 推荐大家!
String nowTime = sdf.format(System.currentTimeMillis());
二、原理:
new Date().getTime() / 1000
System.currentTimeMillis() /1000
new Date().getTime() 和 System.currentTimeMillis() 返回的是一个13位数字,单位是毫秒。除1000能让单位变为秒。
看Date源码 Date 本身就是调用了 System.currentTimeMillis() 来进行初始化
public Date() {
this(System.currentTimeMillis());
}
使用 System.currentTimeMillis() 是直接调用本地方法,而 new Date().getTime() 确还要创建一个Date对象,降低了效率和占用了内存(虽然损耗不大)
三、分别使用 new Date().getTime()
和 System.currentTimeMillis()
获取当前时间的时间戳
// 获取当前时间的时间戳
long timestamp1 = System.currentTimeMillis();
System.out.println("Current time timestamp: " + timestamp1);
// 获取当前时间的时间戳(精确到毫秒)
long timestamp2 = System.currentTimeMillis();
long timestamp = timestamp2 - 10000; // 减去10000,以保留毫秒级别的时间戳
System.out.println("Current time timestamp (milliseconds): " + timestamp);
结果
Current time timestamp: 1647592000
Current time timestamp (milliseconds): 1647592000
需要注意的是,new Date().getTime()
返回的是一个 Date
对象,而 System.currentTimeMillis()
返回的是一个 long
值,其中 long
值是有精度限制的。例如,一些 IDE(集成开发环境)会显示整数表示时间戳,例如 1647592000
,而不是 1647592000.0
。如果需要将时间戳转换为可读的日期和时间格式,可以使用 DateFormat
类。例如,以下代码使用 DateFormat.format()
方法将时间戳转换为年-月-日的格式如下
// 将时间戳转换为年/月/日的格式
String formattedTimestamp = DateFormat.format("yyyy-MM-dd", timestamp);
System.out.println("Formatted date and time: " + formattedTimestamp);
结果
Formatted date and time: 2023-03-13