android - 生成随机的日期和时间 [英] android - generate random date and time

查看:223
本文介绍了android - 生成随机的日期和时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

要触发一些未来的事件,我试图创建一个将执行以下操作的算法:




  • 生成一定量的随机日期格式为 yyyy-mm-dd

  • 以格式 hh为每个日期生成时间: mm:ss 时间应该在9到22小时之间(24小时)

  • 将这些项目添加到String数组。 1个完整的数组条目看起来像 2013-02-25 09:45:23


$ b $我没有明确的想法如何执行这一点。任何建议?

解决方案

确切方案您需要什么..

  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); //这里您可以设置需要的年份范围
int month = RandomDateTime.randBetween(0,11);
int hour = RandomDateTime.randBetween(9,22); //时间将显示在9到22之间
int min = RandomDateTime.randBetween(0,59);
int sec = RandomDateTime.randBetween(0,59);


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

gc.set(年,月,日,小时,最小,秒);

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

}


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

您可以在以下位置找到更多的SimpleDateTime用途: a href =http://docs.oracle.com/javase/6/docs/api/java/text/SimpleDateFormat.html =nofollow> http://docs.oracle.com/javase/6/ docs / api / java / text / SimpleDateFormat.html


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?

解决方案

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

这篇关于android - 生成随机的日期和时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆