Java随机生成时间

  • 知识点:时间的讲解

  • 操作流程:

      >摘要:   第零步:自定义格式
               第一步:得到结束时间的毫秒数
              第二步:得到起始时间的毫秒数
             第三步:用结束时间的毫秒数-起始时间的毫秒数=相隔的毫秒数
            第四步:将相隔的毫秒数随机化+起始毫秒数
           第五步:将毫秒数转化为时间
    
  • get范围时间内的随机时间的code:

package com.mystudy.amuse;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 得到自己想要的具体时间范围
 */
public class GetTime {
    public static void main(String[] args) throws ParseException {
        //第零步:首先肯定要自己规定时间格式
        SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        //这里的parse方法是设置固定时间抛出异常:ParseException

        //第一步:得到结束时间的毫秒数
        //将时间转化成Date类型
        Date endTime=simpleDateFormat.parse("2022-05-21 00:00:00");
        System.out.println(endTime);//Sat May 21 00:00:00 CST 2022
        //这里得到一个Date类型时间,由(Date).gettime得到毫秒数
        //毫秒数很大,故用long接收
        long endSeconds=endTime.getTime();
        System.out.println(endSeconds);//1653062400000

        //第二步:运用同样的方法得到起始时间的毫秒数
        Date startTime=simpleDateFormat.parse("2021-05-21 00:00:00");
        System.out.println(startTime);//Fri May 21 00:00:00 CST 2021
        long startSeconds=startTime.getTime();
        System.out.println(startSeconds);//1621526400000

        //第三步:用结束的毫秒数-起始的毫秒数=相隔的毫秒数
        long apartSeconds=endSeconds-startSeconds;
        
        //第四步:将相隔的毫秒数随机化+起始毫秒数
        long timeSeconds= (long) (apartSeconds*Math.random());
        long realSeconds=startSeconds+timeSeconds;

        //第五步:将毫秒数转化为时间
        String realTime=simpleDateFormat.format(realSeconds);
        System.out.println(realTime);//随机时间:2022-03-31 09:26:16
        Date realTime1=simpleDateFormat.parse(realTime);
        //哎!就害怕你要这种类型的时间
        System.out.println(realTime1);//随机时间:Thu Mar 31 09:26:16 CST 2022
    }
}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值