【问题标题】:Generate random unix timestamp生成随机 unix 时间戳
【发布时间】:2012-06-08 14:57:37
【问题描述】:

如何在特定时间生成随机 unix 时间戳。例如获取今天和明天之间的随机 unix 时间平均值。

【问题讨论】:

标签: java unix-timestamp


【解决方案1】:
long randomEpoch = epoch1 + Math.abs(new Random().nextLong()) % (epoch2-epoch1);

其中epoch1epoch2 是两次。

【讨论】:

  • 非常好!我做到了: new Date(Math.abs(new Random().nextLong()) % new Date().getTime()) 得到 1/1/1970 到今天之间的随机日期
【解决方案2】:

通过生成两个时间戳来获取所需的范围。减去差值(绝对值)。获取 0 到 1 之间的随机数。将差值乘以随机数。将结果添加到较早的时间图。

【讨论】:

    【解决方案3】:

    此代码专门获取今天和明天之间的随机时间。

    public Date randTime(){
        Date now = new Date();
        Date today = new Date(now.getFullYear(), now.getMonth(), now.getDay(), 0, 0, 0, 0);
        return new Date(today.getTime() + (long)(Math.random() * 86400000));
    }
    

    【讨论】:

    • 我想你的意思是(long)(Math.random() * 86400000)
    • 确实如此。毫秒,而不是秒 XD
    猜你喜欢
    • 2012-12-21
    • 2013-06-20
    • 2014-10-28
    • 2010-11-15
    • 1970-01-01
    • 1970-01-01
    • 2018-10-14
    • 2012-06-16
    • 2017-07-13
    相关资源
    最近更新 更多