简体   繁体   English

生成Java日期,但日期不变且时间不同

[英]Generate Java Dates but constant date and different times

I am trying to generate random dates as Java Dates but the date remains the same. 我正在尝试将随机日期生成为Java日期,但是日期保持不变。 I want the time to be random only, not the date. 我只希望时间是随机的,而不是日期。

Eg test case 1: 1/1/2013 9:08:52 例如测试案例1:1/1/2013 9:08:52

test case 2: 1/1/2013 15:01: 42 etc. 测试案例2:1/1/2013 15:01:42等

Any ideas? 有任何想法吗?

hey guys i found something that works. 嗨,我发现了一些可行的方法。 Thanks for the help! 谢谢您的帮助!

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);
    }

}

Use this to find out the start and end Unix timestamps for the date you desire: http://www.epochconverter.com/ 使用它来查找所需日期的Unix起始和结束时间戳记: http : //www.epochconverter.com/

Generate a random long between those two values. 在这两个值之间生成一个随机的long Eventually format the long by using a SimpleDateFormat http://docs.oracle.com/javase/6/docs/api/java/text/SimpleDateFormat.html 最终通过使用SimpleDateFormat http://docs.oracle.com/javase/6/docs/api/java/text/SimpleDateFormat.html格式化long SimpleDateFormat

try 尝试

    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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM