2

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?

Community
  • 1
  • 1
Sid
  • 988
  • 8
  • 27

1 Answers1

4
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()) );
Daniel Aranda
  • 6,426
  • 2
  • 21
  • 28
  • I think the problem may be with DateUtils.format(). The code that you gave works like charm, but it gives jargon when is formatted using that. – Sid Mar 30 '15 at 14:35
  • 1
    Then there is a bug with DateUtil, you should try another Date formatter library like moment.js. We are providing a valid Date object, and they are rendering poorly. – Daniel Aranda Mar 30 '15 at 14:47
  • I started to believe so. Can we not use formatDate and still get output in yyyymmdd format? Is it possible.? – Sid Mar 30 '15 at 14:57
  • I think this should work. I am trying to build more condition around that block like month >12 and day>31. I will accept your answer once I test your code. :) Thanks. – Sid Mar 31 '15 at 13:32