Java代码生成随机日期时间(7月24日至7月30日) - 年-月-日-时-分-秒格式
以下是一个随机生成指定时间范围内的任意时间的Java代码:\n\njava\nimport java.time.LocalDateTime;\nimport java.util.concurrent.ThreadLocalRandom;\n\npublic class RandomDateTime {\n public static void main(String[] args) {\n LocalDateTime startDateTime = LocalDateTime.of(2022, 7, 24, 0, 0, 0);\n LocalDateTime endDateTime = LocalDateTime.of(2022, 7, 30, 23, 59, 59);\n\n long startEpochSecond = startDateTime.toEpochSecond(java.time.ZoneOffset.UTC);\n long endEpochSecond = endDateTime.toEpochSecond(java.time.ZoneOffset.UTC);\n\n long randomEpochSecond = ThreadLocalRandom.current().nextLong(startEpochSecond, endEpochSecond + 1);\n\n LocalDateTime randomDateTime = LocalDateTime.ofEpochSecond(randomEpochSecond, 0, java.time.ZoneOffset.UTC);\n\n String formattedDateTime = randomDateTime.format(java.time.format.DateTimeFormatter.ofPattern("yyyy-MM-dd-HH-mm-ss"));\n System.out.println(formattedDateTime);\n }\n}\n\n\n此代码使用java.time.LocalDateTime类来表示日期和时间,并使用java.util.concurrent.ThreadLocalRandom类生成指定范围内的随机秒数。最后,将生成的随机时间格式化为指定的年-月-日-时-分-秒格式并输出。
原文地址: https://www.cveoy.top/t/topic/p6Hg 著作权归作者所有。请勿转载和采集!