首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Java:在范围之间生成一个随机日期(范围从当前日期/时间开始到未来随机日期(例如从当前日期/时间开始的5-10天)。

Java:在范围之间生成一个随机日期(范围从当前日期/时间开始到未来随机日期(例如从当前日期/时间开始的5-10天)。
EN

Stack Overflow用户
提问于 2017-11-22 20:14:55
回答 1查看 5.2K关注 0票数 2

这里是Java初学者。在搜索和研究之后,我认为这是生成当前日期/时间的最佳方法:

代码语言:javascript
复制
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date date = new Date();
  1. 如何将上述当前日期/时间放入变量中?
  2. 如何从当前日期/时间生成随机的未来日期(例如,随机范围可以是5-10天),这意味着我没有未来日期的固定日期。
  3. 如何将未来日期存储到变量中?

附带说明:我为什么问问题1和问题3,因为我可以使用存储日期的变量来进行比较和计算(用于if-else块)。

非常感谢你的帮助!

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-11-22 20:36:52

您可以使用LocalDateTime代替:

代码语言:javascript
复制
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
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 a 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 the 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);
    }
}

示例输出:

代码语言:javascript
复制
Current Date: 2017/11/22 20:41:03
Random amount of days: 7
Date 7 days in future: 2017/11/29 20:41:03
票数 8
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/47443220

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档