我有一个生成随机日期字符串的代码。然而,我发现当我生成一个随机时间戳时,它包含了一些精确的小数点到秒字段。我的SimpleDateFormat怎么不包含这样的精度值,有人知道这里出了什么问题吗?我如何删除或控制精度值?
代码
long rangeBegin = Timestamp.valueOf("2015-01-01 00:00:00").getTime();
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date currentDate = new Date();
String currentDateString = simpleDateFormat.format(currentDate);
long rangeEnd = Timestamp.valueOf(currentDateString).getTime();
long diff = rangeEnd - rangeBegin + 1;
Timestamp randomTimestamp = new Timestamp(rangeBegin + (long)(Math.random() * diff));
样本输出
randomTimestamp=2015-02-20 02:36:00。646
感谢
编辑:
String randomTimestampString = String.valueOf(randomTimestamp).split("\.")[0];
小数后的数字表示小数精度,即纳秒。您可以通过使用String.substring()方法格式化或简单地剥离它们来消除它。
randomTimestamp=2015-02-20 02:36:00。646
根据时间戳javadoc,646表示精度的纳秒