代码改变世界程序员首页投稿(暂停使用,暂停投稿)

指定日期与时间段生成随机时间

2017-12-21  本文已影响81人  dtgxly

参考文章:www.sharejs.com/codes/java/5918

代码和注释如下:

package com.example.demo;

import java.util.Date;

import java.text.SimpleDateFormat;

public class Test {

    public static void main(String []args) {

        //设置时间格式

        SimpleDateFormat sdfDate = new SimpleDateFormat("yyyy/MM/dd");

        SimpleDateFormat sdfTime = new SimpleDateFormat(" HH:mm:ss");

        //指定日期范围和时间范围

        long date =randomDate("2017/01/01","2017/12/01");

        long time =randomTime("09:00:00","17:00:00");

        String createtime = sdfDate.format(date) + sdfTime.format(time);

        System.out.println(createtime);

    }

    /**

    *生成随机日期

    *@param beginDate起始日期

    *@param endDate结束日期

    *@return

    */

    public static long randomDate(String beginDate, String endDate){

        try{

            SimpleDateFormat format =new SimpleDateFormat("yyyy/MM/dd");

            Date start = format.parse(beginDate);

            Date end = format.parse(endDate);

            if(start.getTime() >= end.getTime()){

                return-1;

            }

            long date =random(start.getTime(),end.getTime());

            return date;

        }catch(Exception e) {

            //TODO Auto-generated catch block

            e.printStackTrace();

        }

        return-1;

    }

    /**

    *生成范围内的随机数

    *@param begin

    *@param end

    *@return

    */

    public static longrandom(longbegin,longend){

        long rtnn = begin + (long)(Math.random() * (end - begin));

        if(rtnn==begin || rtnn==end){

            return random(begin,end);

        }

        return rtnn;

    }

    /**

    * 生成随机时间

    *@param beginTime起始时间

    *@param endTime结束时间

    *@return

    */

    public static long randomTime(String beginTime, String endTime){

    try{

        SimpleDateFormat format =new SimpleDateFormat("HH:mm:ss");

        Date start = format.parse(beginTime);

        Date end = format.parse(endTime);

        if(start.getTime() >= end.getTime()){

            return-1;

        }

        long date =random(start.getTime(),end.getTime());

        return date;

    }catch(Exception e) {

        //TODO Auto-generated catch block

        e.printStackTrace();

    }

        return-1;

    }

}

上一篇下一篇

猜你喜欢

热点阅读