本文主要是介绍LocalDateTime 生成随机的日期,随机时间,随机日期+时间,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
项目测试用例,需要随机生成一一批日期,LocalDateTime怎么实现呢,以下是实现类
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.Random;
import java.util.concurrent.ThreadLocalRandom;/*** @program: ReservedInstance* @description: FastoneDateUtil* @author: sunyuhua* @create: 2021-09-18 15:16**/
public class FastoneDateUtil {/*** 指定开始时间和结束时间,生成指定范围内的时间* @param startTime* @param endTime* @return*/public static LocalTime randomTime(LocalTime startTime, LocalTime endTime) {int startSeconds = startTime.toSecondOfDay();int endSeconds = endTime.toSecondOfDay();int randomTime = ThreadLocalRandom.current().nextInt(startSeconds, endSeconds);return LocalTime.ofSecondOfDay(randomTime);}/*** 生成随机日期* @return*/public static LocalDate randomDay(LocalDate startDate,LocalDate endDate) {Random random = new Random();int minDay = (int)startDate.toEpochDay();int maxDay = (int) endDate.toEpochDay();long randomDay = minDay + random.nextInt(maxDay - minDay);return LocalDate.ofEpochDay(randomDay);}/*** 返回随机的日期和时间* @return*/public static LocalDateTime randomDateTime(){return randomDay(LocalDate.of(2021,9,17),LocalDate.of(2021,9,20)).atTime(randomTime(LocalTime.of(18,0,59),LocalTime.of(19,0,59)));}}
这篇关于LocalDateTime 生成随机的日期,随机时间,随机日期+时间的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!