这个问题在这里已有答案:
我想用javascript和库chancejs创建一个随机日期时间:
import { Chance } from 'chance';
const chance = new Chance();
const now = new Date();
const randomTime = chance.date({ maxTime: now });
我能管理的最好的是从当年减少一个,并在两年之间得到一个随机日期,但我希望今年/日/月也包含在随机性中:
const maxYear = ((new Date()).getFullYear() - 1);
const radomPastDate = chance.birthday({ year: chance.year({ min: 2000, max: maxYear }) }) as Date;
我很欣赏这些想法。
要创建自1970年以来随机的过去日期和时间,您可以使用
const chance = new Chance();
const randomPastDateTime = chance.date({max: new Date()});
console.log(randomPastDateTime);
<script src="http://chancejs.com/chance.min.js"></script>
@ raina77ow建议:
var now=new Date();
var twoyearsago=new Date();
// if you really want to, a twoyearsago.setTime(now.getTime()); could be added here
twoyearsago.setFullYear(twoyearsago.getFullYear()-2);
var randomdate=new Date(now.getTime()
-Math.random()*(now.getTime()-twoyearsago.getTime()));
result.innerText=randomdate;
<div id="result"></div>