I am trying to generate random date in Mirth in the format yyyymmdd, a tool that uses Javascript and Limitedly supports Java (Apache commons).
The problem I am facing is that the date it is generating is outside range.
Some random output my code generated
20131837
20140448
20150100
This is the code I am using
var visit_from=new Date(2012,0,1).getTime();
var visit_to=new Date(2015,0,1).getTime();
var visit_date=DateUtil.formatDate("yyyyddmm",new Date(visit_from + Math.random()*(visit_to-visit_from)));
One low level idea that I am having is to define an array from 1-12 for the month and 1-31 for day, and have Math.random() work on that. But that will not work for Feb. I am planning on using this method if I may not find any other way.
I found a couple of questions like this and this, but they seem to be on C#.
Any suggestions?
function randomDate(){
var startDate = new Date(2012,0,1).getTime();
var endDate = new Date(2015,0,1).getTime();
var spaces = (endDate - startDate);
var timestamp = Math.round(Math.random() * spaces);
timestamp += startDate;
return new Date(timestamp);
}
function formatDate(date){
var month = randomDate().getMonth();
var day = randomDate().getDate();
month = month < 10 ? '0' + month : month;
day = day < 10 ? '0' + day : day;
return String(date.getFullYear()) + month + day;
}
console.log( randomDate() );
console.log( randomDate() );
console.log( randomDate() );
console.log( randomDate() );
//UPDATE: added with date format
console.log( formatDate(randomDate()) );