简体   繁体   English

Java-获取两个日期之间的日期,产生意外结果

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

So i'm trying to get a random time between two set times. 所以我试图在两个设定时间之间获得一个随机时间。 But the resulting date is not what I'm expecting. 但是结果日期不是我所期望的。

I'm expecting a result that is within the two dates I give as the earliest and the latest, but I get a date thats on the next day, and it appears as though if I take the time i'm supposed to get and subtract 12 I get this answer. 我期望得到的结果在我给出的最早和最晚的两个日期之内,但是我得到的日期是第二天,好像我花的时间似乎应该减去12我得到这个答案。 This is the log get: http://prntscr.com/6205yh 这是日志获取: 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;
    }
}`

If someone could explain to me whats going on I would be very grateful. 如果有人可以向我解释发生了什么事,我将不胜感激。

This could be better :) 这可能更好:)

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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