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);
}
}
3条答案
按热度按时间px9o7tmv1#
采取
LocalDateTime.now()
然后以0到86400之间的随机秒数返回时间一般解决方案
定义开始
dates
最后呢计算以秒为单位的差值,得到该范围内的随机整数
使用以下两种方法之一计算随机日期:
从头开始,随机添加秒数
从结尾开始,去掉随机的秒数
2vuwiymt2#
你可以用
calendar.get()
以获取当时的所有信息integers
然后使用rand.nextInt()
创建一个随机时间。试试这个:
此代码的优点是允许您以任何方式自定义输出。
xmakbtuz3#
您可以使用例如date.gettime()将日期转换为最长的日期。这样就得到了一个区间[date1,date2]。接下来,必须使用将其域[0,1]转换为[date1,date2]的函数Mapmath.random()返回的值。