random—在java中,如何将昨天和今天的本地日期时间之间的时间随机化?

ifsvaxew  于 2021-06-27  发布在  Java
关注(0)|答案(3)|浏览(422)

我需要用java随机分配一个时间。
如果现在是时候 24/2/2021 13:56:13 ,然后我需要在 23/2/2021 13:56:13 以及 24/2/2021 13:56:13 . 我不熟悉java中的随机函数,所以我可能需要一些帮助。谢谢你的关注。

px9o7tmv

px9o7tmv1#

采取 LocalDateTime.now() 然后以0到86400之间的随机秒数返回时间

int randomSeconds = new Random().nextInt(3600 * 24);
LocalDateTime anyTime = LocalDateTime.now().minusSeconds(randomSeconds);
System.out.println(anyTime);

一般解决方案
定义开始 dates 最后呢
计算以秒为单位的差值,得到该范围内的随机整数
使用以下两种方法之一计算随机日期:
从头开始,随机添加秒数
从结尾开始,去掉随机的秒数

LocalDateTime periodStart = LocalDateTime.now().minusDays(1);
LocalDateTime periodEnd = LocalDateTime.now();

int randomSeconds = new Random().nextInt((int) periodStart.until(periodEnd, ChronoUnit.SECONDS));

//LocalDateTime anyTime = periodStart.plusSeconds(randomSeconds);
LocalDateTime anyTime = periodEnd.minusSeconds(randomSeconds);
2vuwiymt

2vuwiymt2#

你可以用 calendar.get() 以获取当时的所有信息 integers 然后使用 rand.nextInt() 创建一个随机时间。
试试这个:

import java.util.Calendar;
import java.util.Random;

public class randomDate {

public static void main(String[] args){

Calendar calendar = Calendar.getInstance();
Random rand = new Random();

int year = calendar.get(Calendar.YEAR);  // get year
int month = calendar.get(Calendar.MONTH)+1;  // get month
int today = calendar.get(Calendar.DAY_OF_MONTH);  // get day
int hour_now = calendar.get(Calendar.HOUR_OF_DAY); // get hour
int minutes_now = calendar.get(Calendar.MINUTE);  // get minutes
int rand_minutes = 0;

// random day between today & tomorrow (today < tomorrow < today+2)
int rand_day = rand.nextInt((today+2)-today) + today;

// the random hour between hour_now -> 24 & tomorrow from 00 -> hour_now
int rand_hour_today = rand.nextInt((24)-hour_now) + hour_now;
int rand_hour_tomorrow = rand.nextInt(hour_now+1);
int rand_hour = 0;
int choose = (int) Math.round(Math.random());
if(rand_day == today) {
    rand_hour = rand_hour_today;
}
    else rand_hour = rand_hour_tomorrow;

// if random day is tomorrow then limit rand_hour
if(rand_day == today+1 && rand_hour == hour_now){
    rand_minutes = rand.nextInt(minutes_now);
}
else
rand_minutes = rand.nextInt(60);

int rand_seconds = rand.nextInt(60);

System.out.print("Random time for the next 24 hours: "+ rand_day +"/");
if(month < 10){System.out.print("0");}
System.out.print(+month+"/"+year+"  ");
if(rand_hour < 10){System.out.print("0");}
System.out.print(+rand_hour+":");
if(rand_minutes < 10){System.out.print("0");}
System.out.print(+rand_minutes+":");
if(rand_seconds < 10){System.out.print("0");}
System.out.print(+rand_seconds);
    }
}

此代码的优点是允许您以任何方式自定义输出。

xmakbtuz

xmakbtuz3#

您可以使用例如date.gettime()将日期转换为最长的日期。这样就得到了一个区间[date1,date2]。接下来,必须使用将其域[0,1]转换为[date1,date2]的函数Mapmath.random()返回的值。

相关问题