Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

android - generate random date and time

to trigger some future events I'm trying to create an algorithm which would do the following:

  • generate a certain amount of random dates in format "yyyy-mm-dd"
  • generate time for each date in format "hh:mm:ss" Time should be (24h) between 9 and 22 hours
  • Add those items to a String array. 1 complete array entry looks like "2013-02-25 09:45:23"

I have no clear ideas how to perform this. Any suggestions?

like image 286
Droidman Avatar asked Aug 23 '26 13:08

Droidman


2 Answers

Exact Solution what you need..

public class RandomDateTime {

    public static void main(String[] args) {

        SimpleDateFormat dfDateTime  = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss",Locale.getDefault());
        int year = RandomDateTime.randBetween(1900, 2013);// Here you can set Range of years you need
        int month = RandomDateTime.randBetween(0, 11);
        int hour = RandomDateTime.randBetween(9, 22); //Hours will be displayed in between 9 to 22
        int min = RandomDateTime.randBetween(0, 59);
        int sec = RandomDateTime.randBetween(0, 59);


        GregorianCalendar gc = new GregorianCalendar(year, month, 1);
        int day = RandomDateTime.randBetween(1, gc.getActualMaximum(gc.DAY_OF_MONTH));

        gc.set(year, month, day, hour, min,sec);

        System.out.println(dfDateTime.format(gc.getTime()));

    }


    public static int randBetween(int start, int end) {
        return start + (int)Math.round(Math.random() * (end - start));
    }
}

You can find out more uses of SimpleDateTime at: http://docs.oracle.com/javase/6/docs/api/java/text/SimpleDateFormat.html

like image 187
Ram kiran Pachigolla Avatar answered Aug 26 '26 02:08

Ram kiran Pachigolla


what you can do is using the random function get the random timestamp, I mean you can get the random long value easily and then convert that timestamp to the date object like this

Java simple Timestamp to Date conversion

like image 34
Aashish Bhatnagar Avatar answered Aug 26 '26 02:08

Aashish Bhatnagar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!