我想使用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;
我很欣赏想法。
答案 0 :(得分:1)
要创建自1970年以来的随机过去的日期和时间,您可以使用
adb logcat *:E
const chance = new Chance();
const randomPastDateTime = chance.date({max: new Date()});
console.log(randomPastDateTime);
答案 1 :(得分:0)
@ 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>