Java:在一个范围(从当前日期/时间开始到随机未来日期的范围)之间生成一个随机日期(例如,从当前日期/时间开始5-10天)
这里是Java初学者。在谷歌搜索和研究之后,我认为这是生成当前日期/时间的最佳方法:Java:在一个范围(从当前日期/时间开始到随机未来日期的范围)之间生成一个随机日期(例如,从当前日期/时间开始5-10天),java,date,random,Java,Date,Random,这里是Java初学者。在谷歌搜索和研究之后,我认为这是生成当前日期/时间的最佳方法: DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); Date date = new Date(); 如何将上述当前日期/时间放入变量中 如何从当前日期/时间生成随机的未来日期(例如,随机范围可以是5-10天),这意味着我没有固定的未来日期 如何将未来日期存储到变量中 旁注:为什么我问问题1和3,因为我可以使用存储两个日期的变
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date date = new Date();
import java.time.format.DateTimeFormatter;
import java.time.LocalDateTime;
import java.util.Random;
class Main {
public static void main(String[] args) {
// Declare DateTimeFormatter with desired format
DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss");
// Save current LocalDateTime into a variable
LocalDateTime localDateTime = LocalDateTime.now();
// Format LocalDateTime into a String variable and print
String formattedLocalDateTime = localDateTime.format(dateTimeFormatter);
System.out.println("Current Date: " + formattedLocalDateTime);
//Get random amount of days between 5 and 10
Random random = new Random();
int randomAmountOfDays = random.nextInt(10 - 5 + 1) + 5;
System.out.println("Random amount of days: " + randomAmountOfDays);
// Add randomAmountOfDays to LocalDateTime variable we defined earlier and store it into a new variable
LocalDateTime futureLocalDateTime = localDateTime.plusDays(randomAmountOfDays);
// Format new LocalDateTime variable into a String variable and print
String formattedFutureLocalDateTime = futureLocalDateTime.format(dateTimeFormatter);
System.out.println("Date " + randomAmountOfDays + " days in future: " + formattedFutureLocalDateTime);
}
}
示例输出:
Current Date: 2017/11/22 20:41:03
Random amount of days: 7
Date 7 days in future: 2017/11/29 20:41:03
您已经将当前日期存储在变量中。
new date()
是当前日期,date date
是变量,date date=new date();
将当前日期存储在变量中。到目前为止您做了什么?很好。所有内容都按照要求很好地存储在变量中。并在注释中进行了很好的解释。