[英]Generate Java Dates but constant date and different times
我正在嘗試將隨機日期生成為Java日期,但是日期保持不變。 我只希望時間是隨機的,而不是日期。
例如測試案例1:1/1/2013 9:08:52
測試案例2:1/1/2013 15:01:42等
有任何想法嗎?
嗨,我發現了一些可行的方法。 謝謝您的幫助!
import java.util.Random;
import java.sql.Time;
public class Clock2 {
public static void main(String[] args) {
for (int i=0; i< 100; i++){
final Random random = new Random();
final int millisInDay = 24*60*60*1000;
Time time = new Time((long)random.nextInt(millisInDay));
System.out.println(time);
}
}
使用它來查找所需日期的Unix起始和結束時間戳記: http : //www.epochconverter.com/
在這兩個值之間生成一個隨機的long
。 最終通過使用SimpleDateFormat
http://docs.oracle.com/javase/6/docs/api/java/text/SimpleDateFormat.html格式化long
SimpleDateFormat
嘗試
Random r = new Random();
GregorianCalendar c = new GregorianCalendar(r.nextInt(100) + 2000, r.nextInt(11), r.nextInt(31));
long t0 = c.getTimeInMillis();
for(int i = 0; i < 10; i++) {
Date d = new Date(t0 + r.nextInt(24 * 3600 * 1000));
System.out.println(d);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.