本文實(shí)例為大家分享了java隨機(jī)生成時(shí)間字符串的具體代碼,供大家參考,具體內(nèi)容如下
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
|
package com.wechat.utils; import java.text.SimpleDateFormat; import java.util.Date; /** * Created by hexun on 2017/2/4. */ public class RandTimeUtils { /** * 生成隨機(jī)時(shí)間 * @param beginDate * @param endDate * @return */ private static Date randomDate(String beginDate,String endDate ){ try { SimpleDateFormat format = new SimpleDateFormat( "yyyy-MM-dd" ); Date start = format.parse(beginDate); //構(gòu)造開始日期 Date end = format.parse(endDate); //構(gòu)造結(jié)束日期 //getTime()表示返回自 1970 年 1 月 1 日 00:00:00 GMT 以來此 Date 對(duì)象表示的毫秒數(shù)。 if (start.getTime() >= end.getTime()){ return null ; } long date = random(start.getTime(),end.getTime()); return new Date(date); } catch (Exception e) { e.printStackTrace(); } return null ; } private static long random( long begin, long end){ long rtn = begin + ( long )(Math.random() * (end - begin)); //如果返回的是開始時(shí)間和結(jié)束時(shí)間,則遞歸調(diào)用本函數(shù)查找隨機(jī)值 if (rtn == begin || rtn == end){ return random(begin,end); } return rtn; } public static void main(String[] args){ Date randomDate=randomDate( "2010-09-20" , "2017-02-04" ); SimpleDateFormat format = new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss" ); String resulttime = format.format(randomDate); //構(gòu)造開始日期 System.out.println(resulttime); } } |
以上就是本文的全部內(nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持服務(wù)器之家。
原文鏈接:http://blog.csdn.net/u014756827/article/details/54861304