触发我试图创建一个算法会做以下一些未来事件:机器人 - 随机生成的日期和时间
- 产生一定量的格式随机日期的“
yyyy-mm-dd
” - 以格式“
hh:mm:ss
”生成每个日期的时间时间应该在9到22小时之间(24h) - 将这些项目添加到字符串数组中。 1完整阵列条目看起来像“
2013-02-25 09:45:23
”
我没有明确的想法如何执行此操作。有什么建议么?
触发我试图创建一个算法会做以下一些未来事件:机器人 - 随机生成的日期和时间
yyyy-mm-dd
”hh:mm:ss
”生成每个日期的时间时间应该在9到22小时之间(24h)2013-02-25 09:45:23
”我没有明确的想法如何执行此操作。有什么建议么?
精确解你需要什么..
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));
}
}
你可以找到SimpleDateTime的更多的用途:http://docs.oracle.com/javase/6/docs/api/java/text/SimpleDateFormat.html
'randBetween'方法给出的边界值只有间隔内值的一半概率。 – Henry 2013-02-20 10:06:08
这个想法很简单。您可以使用Date(milis)构造函数和随机数生成器生成随机日期和时间。你必须找到下限和上限,并从中间随机选择一个数字。
格式化日期和时间非常简单,您可以使用DateFormat类来完成此操作。
你所能做的就是利用随机函数得到随机时间戳,我的意思是,你可以很容易地获得随机的长值,然后该时间戳转换为日期对象这样
生成RA ndom在期望的范围内变长,并将它们转换为'new Date(long)'的日期并根据需要进行格式化? – Henry 2013-02-20 09:41:24