android – 生成随机日期和时间
触发一些未来事件我正在尝试创建一个算法,它将执行以下操作:
- 以“
yyyy-mm-dd
”格式生成一定数量的随机日期 - 以“
hh:mm:ss
”格式为每个日期生成时间。时间应为(24h)9到22小时之间 - 将这些项添加到String数组中。 1个完整的数组条目看起来像“
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)); } }
您可以在以下url找到SimpleDateTime的更多用法: http : //docs.oracle.com/javase/6/docs/api/java/text/SimpleDateFormat.html
你可以做的是使用随机函数获取随机时间戳,我的意思是你可以轻松获得随机长值,然后将该时间戳转换为日期对象,就像这样
Java简单时间戳到日期转换
这个想法很简单。 您可以使用Date(milis)构造函数和随机数生成器来生成随机日期和时间。 你必须找到下限和上限并从中间随机选择一个数字。
格式化日期和时间非常简单,您可以使用DateFormat类来完成此操作。