当前位置: 动力学知识库 > 问答 > 编程问答 >

java - Creating a random epoch value ranging from X days ago and now

问题描述:

Trying to create an epoch value, in Java, where returned value is between now and 14 days ago.

I'm using java.util.Random.nextInt(value) and passing in 1209600, basically 14 days.

But the returned value is never older then today, how come?

public class Debug {

private static final Random rng = new Random();

public static void main(String[] args) {

long now = System.currentTimeMillis();

long timeSinceLastVisit = rng.nextInt(14 * 24 * 60 * 60);

long timeOfLastVisit = now - timeSinceLastVisit;

String date = new java.text.SimpleDateFormat("MM/dd/yyyy HH:mm:ss").format(new java.util.Date (timeOfLastVisit));

System.out.println("1. " + timeOfLastVisit);

System.out.println(date);

}

}

5 sample outputs:

1. 1397057814065

04/09/2014 16:36:54

1. 1397058754779

04/09/2014 16:52:34

1. 1397058553618

04/09/2014 16:49:13

1. 1397058294674

04/09/2014 16:44:54

1. 1397058408390

04/09/2014 16:46:48

网友答案:

You are supposed to use milliseconds, and in the line

long timeSinceLastVisit = rng.nextInt(14 * 24 * 60 * 60);

you are just getting "seconds". To solve this, multiply by 1000 so you get a value that represents milliseconds:

long timeSinceLastVisit = rng.nextInt(14 * 24 * 60 * 60 * 1000);

Sample Outputs:

04/01/2014 21:56:04
04/03/2014 21:44:41
04/07/2014 05:38:58
03/29/2014 22:19:29
04/02/2014 08:54:51
网友答案:

Confusion about milliseconds and seconds was the reason here as recognized before but I would suggest a slightly modified solution to achieve two goals:

  1. output only in full seconds (see the wished format pattern)
  2. more stability regarding integer overflow (imagine, OP wants to change 14 to maybe 100)

    long timeSinceLastVisit = rng.nextInt(14 * 24 * 60 * 60) * 1000L;

分享给朋友:
您可能感兴趣的文章:
随机阅读: