Java - 获取两个日期之间的日期,给出意想不到的结果

Java -Get a Date between two Dates, Giving unexpected result

所以我试图在两个设定时间之间获得一个随机时间。但是结果日期不是我所期望的。

我期望结果在我给出的最早和最晚的两个日期内,但我得到的日期是第二天,看起来好像我花时间应该得到并减去 12 我得到了这个答案。 这是日志获取:http://prntscr.com/6205yh

private long nextLong(Random rng, long n) { long bits, val; do { bits = (rng.nextLong() << 1) >>> 1; val = bits % n; } while (bits - val + (n - 1) < 0L); return val; }

@SuppressWarnings("deprecation")
public Calendar getNextDate() {
    try
    {
        Calendar now = Calendar.getInstance(Locale.getDefault());
        String earliest = getConfig().getString("Date.Spawn Earliest");
        String latest = getConfig().getString("Date.Spawn Latest");

        // Format the hours and minutes into dates
        SimpleDateFormat format = new SimpleDateFormat("HH:mm");
        Date earliestDate = format.parse(earliest);
        Date latestDate = format.parse(latest);

        // Figure out the random time between the two
        long e = earliestDate.getTime();
        long l = latestDate.getTime();
        long d = nextLong(new Random(), l - e) + e;
        Date date = new Date(d);

        // Update the hours and minutes into a new Calander with todays day,month and year.
        Calendar then = Calendar.getInstance(Locale.getDefault());
        System.out.println(date.getHours()+":"+date.getMinutes());
        then.set(Calendar.HOUR, date.getHours());
        then.set(Calendar.MINUTE, date.getMinutes());

        // If it is later then the random time and nows hours are still higher then the latest time; add 7 days to get next week
        if (now.after(then) && now.getTime().getHours() > latestDate.getHours())
            then.add(Calendar.DAY_OF_MONTH, 7);

        System.out.println("At the moment it is:  " + now.getTime().toString());
        System.out.println("Dragon will spawn at: " + then.getTime().toString());

        return then;
    }
    catch (ParseException e)
    {
        // TODO Auto-generated catch block
        e.printStackTrace();
        return null;
    }
}`

如果有人能向我解释这是怎么回事,我将不胜感激。

这可能会更好:)

Date dateStart;
Date dateEnd;
int diff = (int) (dateEnd.getTime() - dateStart.getTime());
Date randomDate = new Date(dateStart.getTime()
      + new Random(System.currentTimeMillis()).nextInt(diff));
Calendar then = Calendar.getInstance();
then.setTime(randomDate);