David Deedech
David Deedech

Reputation: 21

How to generate number where digits on specific position must be from certain range?

I want to write a program that randomly generates an 11 digits number, where the first six digits are YYMMDD which represents a year, a month and a day. For example: 931231.

this is my code

long min = 30000000000L;
long max = 99000000000L;
long res=min +(long)(Math.random() * ((max - min) + 1));

Upvotes: 2

Views: 110

Answers (3)

priyanksriv
priyanksriv

Reputation: 1154

Two parts to it:

  1. Generate first six chars using random epoch time and date format: random value between epoch and current time, extract local date, and format to string.

  2. Generate last five random digits

  public String getRandom() {
    Long randomEpochTime = ThreadLocalRandom.current()
        .nextLong(Instant.now().toEpochMilli());

    String firstSix = Instant
        .ofEpochMilli(randomEpochTime)
        .atZone(ZoneId.systemDefault())
        .toLocalDate()
        .format(DateTimeFormatter.ofPattern("yyMdd"));

    String lastFive = String.valueOf(ThreadLocalRandom.current().nextInt(100000));

    return firstSix.concat(lastFive);
  }

Upvotes: 1

WJS
WJS

Reputation: 40047

To generate the date portion start by declaring an int number = 0

First, generate the year, add that to number and multiply by 100

Then generate the month and add that to the number and multiply by 100

Using the month as a value, select the appropriate number of days for given month and return a value and add it to number.

Example.

int number = 0;
number += 93*100; //number = 9300
number += 12*100; //number = 931200
number += 31; number = 931231;

A similar approach can be used to tack on the other 5 digits. Or do the following:

int othernumber = 321;
String v = String.format("%d%05d", number, othernumber);
long longv = Long.parseLong(v);
System.out.println(longv);

Upvotes: 0

Pavel
Pavel

Reputation: 1647

If I understood correctly your question, you are trying to generate a number representing a random date, if this is the case, you can try the following:

Random rand = new Random();
SimpleDateFormat dateFormat = new SimpleDateFormat("yyMMdd");
long res = Long.parseLong(dateFormat.format(new Date(rand.nextLong())) + (long) (Math.random() * 100000));

Upvotes: 2

Related Questions