Apex——获取两个Date之间的随机时间
废话不多说了,标题已经说得很清楚了,直接看代码吧。
public class GetRandomDate {
/**
获取随机时间 */
public static Date randomDate(Date beginDate,Date endDate){
try {
// Convert to DateTime values
DateTime mint = beginDate;
Datetime maxt = endDate.addDays(1);
// Then convert to milliseconds since Jan 1, 1970, and get difference in ms
Long minms = mint.getTime(), maxms = maxt.getTime(), diff = maxms - minms;
// Return a date between minms and maxms.
//return DateTime.newInstance(minms + Math.mod(Math.abs(Crypto.getRandomLong()), diff)).date();
DateTime dT = DateTime.newInstance(minms + Math.mod(Math.abs(Crypto.getRandomLong()), diff));
System.debug('两date之间的随机时间:' + Date.newInstance(dT.year(), dT.month(), dT.day()));
return Date.newInstance(dT.year(), dT.month(), dT.day());
} catch (Exception e) {
System.debug('An exception occurred:' + e.getMessage());
}
return null;
}
}
此代码估计以后也经常用到,因此做个简单的笔记,也希望对搜到这片文章的你有所帮助。
如果代码测试不够准确或者有其他的好的解决办法也欢迎留言讨论,共勉!
Thx!!